Test case 4

Write Underflow. We dynamically allocate a buffer with malloc(3), decrement the pointer, and then write into that memory location—a write or buffer underflow bug:

/* test case 4 : out-of-bounds : write underflow */static void write_underflow(void){    char *p = malloc(8);    if (!p)        FATAL("malloc failed\n");    p--;    strncpy(p, "abcd5678", 8); /* Bug: write underflow */    free(++p);}

In this test case, we don't want the free(3) to fail, so we ensure the pointer passed to it is correct. The compiler does not detect any bug here; at runtime though, it does indeed crash, with modern glibc detecting errors (in this case, memory corruption):

$ ./membugs 4double free or corruption (out)Aborted$ 

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.