r/ProgrammerHumor 2d ago

Meme bugIntroducedDebugging

Post image
1.1k Upvotes

120 comments sorted by

View all comments

348

u/AdBrave2400 2d ago

Is the mistake that they're allocating 1 byte and storing in a pointer to an int which is 4 bytes?

158

u/atanasius 2d ago

It's allowed to assign to a pointer if it's not dereferenced. Malloc always returns a valid pointer.

24

u/EntitledPotatoe 2d ago

Malloc can return a null pointer if the operation fails. This can be the case if, afaik, for example, there is no more heap available and the OS is not capable of swapping or freeing some other memory for some reason

17

u/atanasius 2d ago

A null pointer is still valid to assign to a variable.

17

u/SeriousPlankton2000 2d ago

Also it's valid to call free(NULL)

4

u/meat-eating-orchid 2d ago

has it always been valid? I could have sworn that freeing a nullpointer was only valid in C++ but not in C. I couldn't find anything on cppreference on when this was introduced or if it has always been like this

10

u/GoddammitDontShootMe 2d ago

Very certain you could always free(NULL); in C. In fact, it's good practice to set pointers to NULL after freeing them to avoid issues like double-free.