Test case 11

Memory leakage - case 1: a (simple) memory leak test case. See the following code snippet:

static const size_t BLK_1MB = 1024*1024;
[...]
static void amleaky(size_t mem)
{
char *ptr;

ptr = malloc(mem);
if (!ptr)
FATAL("malloc(%zu) failed ", mem);

/* Do something with the memory region; else, the compiler
* might just optimize the whole thing away!
* ... and we won't 'see' the leak.
*/
memset(ptr, 0, mem);

/* Bug: no free, leakage */
}

[...]
/* test case 11 : memory leak test case 1: simple leak */
static void leakage_case1(size_t size)
{
printf("%s(): will now leak %zu bytes (%ld MB) ",
__FUNCTION__, size, size/(1024*1024));
amleaky(size);
}

[...]

case 11:
leakage_case1(32);
leakage_case1(BLK_1MB);
break;
[...]

As one can clearly see, in the amleaky function, the ptr memory pointer is a local variable and is thus lost once we return from the buggy function; this makes it impossible to free it later. Also notice—the comment explains it—how we require memset to force the compiler to generate code for and use the memory region.

A quick build and execution of the preceding test case will reveal that, again, no obvious compile-time or runtime detection of the leakage occurs:

$ ./membugs 2>&1 | grep "memory leak"
option = 11 : memory leak test case 1: simple leak
option = 12 : memory leak test case 2: leak more (in a loop)
option = 13 : memory leak test case 3: lib API leak
$ ./membugs 11
leakage_case1(): will now leak 32 bytes (0 MB)
leakage_case1(): will now leak 1048576 bytes (1 MB)
$

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset