r/ProgrammerHumor 2d ago

Meme bugIntroducedDebugging

Post image
1.1k Upvotes

120 comments sorted by

View all comments

339

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?

155

u/atanasius 2d ago

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

53

u/vishal340 2d ago

but accessing it will be issue right?

39

u/backfire10z 2d ago

Likely not. Malloc guarantees that the passed-in size is the minimum number of bytes it allocates, but not the maximum. You’d likely get some minimum sized chunk, somewhere between 16-32 bytes depending on the system as far as I understand it.

42

u/atanasius 2d ago

Implementations are allowed to specify behavior that is otherwise undefined.

I looked up a C24 draft and it's actually stricter:

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and size less than or equal to the size requested.

So a pointer returned by malloc(1) is not necessarily valid for int*.

-1

u/p88h 2d ago

Aligned means int sized at minimum.

The actual allocated size is much bigger anyways, but it will be a multiple of 8 bytes on a 64 bit system, and 'usable' part of that will be at least 8 bytes, and typically you will be able to read at least 16 without a page fault.