Moksh Bansal
Moksh Bansal

Reputation: 1

Having a problem with free function in C?

I am a beginner at coding and have a problem with my code. please advice.

Input:-

#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;

   for (int i = 0; i < 3; i++)
   {
       printf("%i\n", list[i]);
   }

    int *tmp = realloc(list, 4 * sizeof(int));
    if (tmp == NULL)
    {
        free(list);
        return 1;
    }

    free(list);

    tmp[3] = 4;

    list = tmp;

    for (int i = 0; i < 4; i++)
    {
        printf("%i\n", list[i]);
    }

    free(tmp);
}

Output:-

1
2
3
1628405245
5
-136327152
4

I am having a problem with free(list); if i remove it, then the code seems to work fine,

but if i do this (Which is done in CS50's lecture)

tmp[3] = 4;

free(list);

Then the error comes

1
2
3
1508201014
5
1428381712
21918
free(): double free detected in tcache 2
zsh: abort      ./list1

Why is this please Explain?

Upvotes: 0

Views: 125

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

According to the C Standard (7.22.3.5 The realloc function)

2 The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size.

and

  1. ...If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

Thus the last call of free in this code snippet

int *tmp = realloc(list, 4 * sizeof(int));
if (tmp == NULL)
{
    free(list);
    return 1;
}

free(list);

invokes undefined behavior because the memory for the old object pointed to by the pointer list was already freed in this successful call of realloc

int *tmp = realloc(list, 4 * sizeof(int));

You need to remove the last call of free in this code snippet.

Also in this code snippet

tmp[3] = 4;

free(list);

the call of free invokes undefined behavior by the same reason.

Pay attention to that realloc can return the same address of the reallocated memory or a new address of the reallocated memory. This can influence on the result of undefined behavior.

Upvotes: 1

Related Questions