C Debugging Note
Updating
Memory leak
Things that could result in a memory leak :
- Assigning NULL to a dynamically allocated memory block. Will not be freed later.
char ** arg = calloc(1, sizeof(char *));
arg[0] = calloc(10, sizeof(char));
arg[0] = NULL;
free(arg); // MEMORY LEAK!
-
Rewriting to a freed memory block.
In some weird cases, the programme will run smoothly for several steps (writing) and then throw a segmentation fault error.
To save yourself some time from debugging memory leak issues, here are the things you can do:
-
Always draw a diagram for the changes you made to the dynamically allocated blocks
-
Attach debugging messages to each operation on the dynamically allocated blocks. Use debug flags.
An ultimate wisdom:
The most important thing is to get it run with no error whatsoever, but not to do research on the cause of the problem.
Therefore, if you have stuck for some time, re-write the piece of code -- rewriting always solves the problem.