C/C++ Arena

Step 6 of 9

Memory bugs to avoid

The classic heap mistakes, which C won't catch for you:

Bug What happens
Leak forgetting free; memory is lost until the program exits
Use after free using a pointer after free; it may point at reused memory
Double free freeing twice; corrupts the allocator
Out of bounds writing past the end; silently corrupts neighbours

A good habit: set a pointer to NULL right after freeing it. free(NULL) is safe and does nothing.

Your turn: this function should build a message but it has two memory bugs (a missing + 1 for the terminator, and a leak of tmp). Fix both so it returns "gg wp" correctly.

Previous: Growing with realloc Next: A 2D grid on the heap