Test case 8

Use After Free (UAF). Operating upon a memory pointer after it has been freed up is obviously a bug, causing UB. The pointer is sometimes called a dangling pointer. Here is a quick test case:

/* test case 8 : UAF (use-after-free) test case */static void uaf(void){    char *arr, *next;    char name[]="Hands-on Linux Sys Prg";    int n=512;    arr = malloc(n);    if (!arr)        FATAL("malloc failed\n");    memset(arr, 'a', n);    arr[n-1]='\0';    printf("%s():%d: arr = %p:%.*s\n", __FUNCTION__, __LINE__, arr,                32, arr);    next = malloc(n);    if (!next) {        free(arr);        FATAL("malloc failed\n");    }    free(arr);    strncpy(arr, name, strlen(name));  /* Bug: UAF */    printf("%s():%d: arr = %p:%.*s\n", __FUNCTION__, __LINE__, arr,                32, arr);    free(next);}

Again, neither at compile-time ...

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.