Why heap memory still accessible after HeapFree

395 views Asked by At

I wrote a simple C program which creates a singly linked list. It works; for instance, I pushed a few numbers to a list and the function print_list(...) prints the numbers to the console.

However, I then added a clear_list(...) function and called it before print_list(...) to see what would happen. After the call to clear_list, print_list still prints numbers as before.

How does print_list print numbers from freed memory? I use HeapAlloc for allocation of the list structure and HeapFree to deallocate.

Code below:

static BOOL push_list(DWORD a)
{
    LIST *ptr = NULL;

    ptr = (PLIST)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,     sizeof(LIST));
    if (ptr == NULL)
    {
        printf("Error push list\n");
        return FALSE;
    }

    ptr->i = a;

    ptr->next = LIST_HEAD;
    LIST_HEAD  = ptr;


    return TRUE;
}



void free_dir_list(void)
{
    PLIST pTemp = NULL;
    P_LIST PTR = LIST_HEAD;


    while (PTR != NULL)
    {
        pTemp = PTR;
        PTR = PTR->next;
        HeapFree(GetProcessHeap(), 0, pTemp);
    }
}
1

There are 1 answers

0
jwezorek On

Using deallocated memory is undefined behavior in C.

It works here because nothing has altered the memory after it was deallocated. This is usually the case immediately after memory is deallocated. Functions like HeapFree(...) or just the standard C free(...) do not commonly zero out the memory; they just alter internal state managed by the runtime such that the memory is known to be free.