Common Errors
Explore common errors involved in dynamic memory management using malloc() and free() in C. Understand why issues such as forgetting allocation, buffer overflows, uninitialized memory reads, memory leaks, dangling pointers, and double frees occur. Learn the importance of proper memory handling for stable programs and discover tools that help detect memory-related problems.
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):
When you run the code above, it will likely lead to a
Alternately, you could use strdup() and make your life even easier. Read the strdup man page for more information.
TIP: IT COMPILED OR IT RAN ...