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):

Get hands-on with 1200+ tech skills courses.