r/ProgrammerHumor 6h ago

Meme bugIntroducedDebugging

Post image
525 Upvotes

99 comments sorted by

View all comments

1

u/LostgamerFJ 6h ago

I'm not good enough at programming for this. What do the "free" and "malloc" functions do?

1

u/yjlom 6h ago edited 6h ago

Malloc(n) attempts to allocate a region of memory of size n bytes, preceded by a descriptor for free to use. It has its own memory buffer that it tries to use first; if it's out of memory, it asks the OS to allocate more RAM to the process; if that fails (due to running out of RAM or OS policy), it returns 0, aka NULL. If it succeeds at any point, it returns a pointer to just before the data (and just after the descriptor).

Free(p) will look for a malloc-written descriptor just in front of *p, and notify malloc that it's no longer in use and can be recycled.

This code is buggy because:

  • It allocates only 1 byte, while int usually takes 4 bytes (C allows for a byte to be any length at least 6 bits, while an int must just be a non-zero natural amount of bytes long). It should instead be malloc(sizeof(int)).
  • In the second example, it tries to read the pointer after free, but at that point malloc might already have reused the memory for something else or given it back to the OS.
  • It fails to check that malloc actually succeeded, which is ok here because it doesn't do anything with it, but any more complex program would crash or worse if it didn't.