Common Errors
Learn to avoid common pitfalls when dealing with dynamic memory allocations.
We'll cover the following...
Memory leaks
We’ve already discussed memory leaks quite extensively. However, this is such an important concept that we’ll reiterate it. Pretty much everyone can write code with dynamic memory allocations, but not everyone can write it correctly.
Let’s look at the case of strdup
and investigate a memory leak. In the following code, we duplicate a string using strdup
, but we never free the memory.
Recall that strdup
dynamically allocates a copy and returns it to the caller, which is responsible for freeing the memory.
Press + to interact
#include <stdio.h>#include <string.h>#include <stdlib.h>int main(){char *str = "Hello, World!";printf("str = [%s]\n", str);char *duplicate = strdup(str);printf("duplicate = [%s]\n", duplicate);return 0;}
Let’s look at the Valgrind output:
==17== Memcheck, a memory error detector
==17== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==17== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==17== Command: ./main
==17== Parent PID: 11
==17==
==17==
==17== HEAP SUMMARY:
==17== in use at exit: 14 bytes in 1 blocks
==17== total heap usage: 2 allocs, 1 frees, 4,110 bytes allocated
==17==
==17== 14 bytes in 1 blocks are definitely lost in loss record 1 of 1
==17== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==17== by 0x48ED38E: strdup (strdup.c:42)
==17== by 0x1091A3: main (main.c:10)
==17==
==17== LEAK SUMMARY:
==17== definitely lost: 14 bytes in 1 blocks
==17== indirectly lost: 0 bytes in 0 blocks
==17== possibly lost: 0 bytes in 0 blocks
==17== still reachable: 0 bytes in 0 blocks
==17== suppressed: 0 bytes in 0 blocks
==17==
==17== For lists of detected and suppressed errors, rerun with: -s
==17== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
It’s clear that the code leaks memory. The interesting part is this one:
==17== 14 bytes in 1 blocks are definitely lost in loss record 1 of 1
==17== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==17== by 0x48ED38E: strdup (strdup.c:42)
==17== by 0x1091A3: main
...