r/ProgrammerHumor 2d ago

Meme bugIntroducedDebugging

Post image
1.1k Upvotes

120 comments sorted by

View all comments

45

u/PR8-E 2d ago

int* x = (int*) malloc(sizeof(int)); Since malloc returns void pointer you should parse it to type you use.

36

u/yjlom 2d ago

void * coerces to any pointer type. This is valid: int *x = malloc(sizeof(int));. This is also valid (in C23): auto x = (int *) malloc(sizeof(int));.

2

u/mydogatethem 2d ago

Is this different between C and C++? In C++ you absolutely cannot assign a void* to an int* without casting it. You can always do the reverse: a void* can be assigned any type of pointer.

4

u/vetgirig 2d ago

In C++ you do not really use "malloc", In C++ you use "new" instead.

1

u/mydogatethem 2d ago

I mean… yes you do, but not really. There are use cases for both. Not everything is a class and not every API you call is even going to work with that buffer you pass in unless the API can free() it. See posix for example.

Anyways, that wasn’t the question I asked and is not even relevant to the question I asked.