Common Errors

This lesson briefly discusses the common errors that you may encounter with the usage of 'malloc' and 'free' calls.

There are a number of common errors that arise in the use of malloc() and free(). Here are some we’ve seen over and over again in teaching the undergraduate operating systems course. All of these examples compile and run with nary a peep from the compiler; while compiling a C program is necessary to build a correct C program, it is far from sufficient, as you will learn (often in the hard way).

Correct memory management has been such a problem, in fact, that many newer languages have support for automatic memory management. In such languages, while you call something akin to malloc() to allocate memory (usually new or something similar to allocate a new object), you never have to call something to free space; rather, a garbage collector runs and figures out what memory you no longer have references to and frees it for you.

Forgetting to allocate memory

Many routines expect memory to be allocated before you call them. For example, the routine strcpy(dst, src) copies a string from a source pointer to a destination pointer. However, if you are not careful, you might do this (lines 4-6):

Press + to interact
#include<stdio.h>
int main() {
char *src = "hello";
char *dst; // oops! unallocated
strcpy(dst, src); // segfault and die
return 0;
}

When you run the code above, it will likely lead to a segmentation faultAlthough it sounds arcane, you will soon learn why such an illegal memory access is called a segmentation fault; if that isn’t incentive to read on, what is?, which is a fancy term for YOU DID SOMETHING WRONG WITH MEMORY, YOU FOOLISH PROGRAMMER AND I AM ANGRY. In this case, the proper code might instead look like this (lines 4-6):

Press + to interact
#include<stdio.h>
int main() {
char *src = "hello";
char *dst = (char *) malloc(strlen(src) + 1);
strcpy(dst, src); // work properly
printf("dst: %s",dst);
return 0;
}

Alternately, you could use strdup() and make your life even easier. Read the strdup man ...

Access this course and 1400+ top-rated courses and projects.