In Unix/C programs, understanding how to allocate and manage memory is critical in building robust and reliable software. What mistakes should be avoided?
Forgetting To Allocate Memory
1 | char *src = "hello"; |
Not Allocating Enough Memory
1 | char *src = "hello"; |
Forgetting to Initialize Allocated Memory
Forgetting to Free Memory
_Also known as memory leak_
Freeing Memory Before You Are Done With It
Freeing Memory Repeatedly
Calling Free() Incorrectly
Means that free() expects you only to pass to it one of the pointers you received from malloc() earlier. However you passed in some other value, bad things can(and do) happen.
Because of frequent errors with memory, a whole ecosphere of tools have developed to help find such problems in your code. Check out both purify and valgrind; both are excellent at helping you locate the source of your memory-related problems.
For a cool modern paper on how to detect and correct many of these problems automatically, see Exterminator: Automatically Correcting Memory Errors with High Probability