Search code examples
cmemory-corruption

Freeing Node from LinkedList ( memory wise )


When send the head of a list to a function that free()s the memory. The given error by the compiler is:

"HEAD CORRUPTION DETECTED: after Normal block (#70) at 0x011BCC0
CRT detected that the application wrote to memory after end of head buffer. "

I tried to free() only the first node just to see how it goes but its the same error.
The function the receiving the linkedlist itself:

void freeListOfEmployees(EmployeeNode *head)
{
    EmployeeNode *ptr = head, *temp = NULL;

    while (ptr != NULL) { 
        temp = ptr; 
        ptr = ptr->next; 
        free(temp); 
    }

    head = NULL;
}

Solution

  • The problem is not in freeListOfEmployees but in createEmployeeNode, more specicially in this line:

    EmployeeNode *temp = (EmployeeNode *)malloc(sizeof(EmployeeData));
    ^^^^^^                                             ^^^^^^
    

    You are allocating memory for an EmployeeNode but you ask for the size of an EmployeeData.

    This would be correct:

    EmployeeNode *temp = (EmployeeNode *)malloc(sizeof(EmployeeNode));
    

    or better:

    EmployeeNode *temp = (EmployeeNode *)malloc(sizeof *temp);
    

    or even better:

    EmployeeNode *temp = malloc(sizeof *temp);
    

    This way there is no possibility to get the size wrong.

    And the cast (EmployeeNode*) is not completly wrong, but useless.

    And anticipating your next question: why did the problem only occur in freeListOfEmployees and not before?

    Answer: because you're overwriting memory that does not belong to you which triggers so called "undefined behaviour", and once undefined behaviour has been triggerd, anything can happen. Undefine bahaviour includes "apparently woring fine".