0

In order to solidify concepts from the lectures, I usually run some of the source code in my ide and play around with it a little bit.

During lecture 5 around the 55 minute mark, Professor Malan changes malloc to realloc, and gets rid of the for loop under it.

When I try running this code exactly as shown in the lectures, it returns

0

0

32808976

0

free(): double free detected in tcache 2

Aborted (core dumped)

Curious what caused this error message.

#include <stdio.h>
#include <stdlib.h>
      
int main(void)
{
    int *list = malloc(3 * sizeof(int));
    if (list == NULL)
    {
        return 1;
    }
    
    list[0] = 1;
    list[1] = 2;
    list[2] = 3;
    
    int *tmp = realloc(list, 4 * sizeof(int));
    if (tmp == NULL)
    {
        free(list);
        return 1;
    }
    
    tmp[3] = 4;
    
    free(list);
    
    list = tmp;
    
    for (int i = 0; i < 4; i++)
    {
        printf("%i\n", list[i]);
    }
    
    free(list);
    
}

1 Answer 1

1

The problem is the free list command following the temp[3] assignment. It breaks the program.

At that point, list contains the address of the reallocated memory. So, that memory is deallocated. The work with tmp that follows is unpredictable at best. Since the address in tmp is assigned to list, list now contains the same address that was freed. In short, it's all corrupted by the free(list) code.

Prof. Malin partially addressed the issue as the lecture proceeded, but didn't deal with this.

The code may or may not have worked based on the following.

If there is sufficient memory available following the original memory, realloc may use it to do the reallocation and would then return the same address. If there isn't enough memory available, it will return a new address, after copying all the stored data to the new address.

So, if realloc were to return a new address, this error might not have happened. But, it might still throw a double free because the original memory had been deallocated by the realloc command previously. I haven't figured out how to test and verify this.

In any case, the free command is what is breaking this code.

Comment that line out and it works as expected.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .