Common Memrory Errors

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
2
3
char *src = "hello";
char *dst; // oops! unallocated
strcpy(dst, src); //segfault and die

Not Allocating Enough Memory

1
2
3
char *src = "hello";
char *dst = (char*) malloc(strlen(src)); // too small, should be strlen(src) + 1.
strcpy(dst, src);

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