2

As per my understanding realloc may be extending block of already given memory (if it is possible) or, otherwise, allocate a completely new block of memory and copy given input. Can someone explain why the below code is throwing an double free error?

void test(int *b) {

    b = realloc(b, 10 * sizeof(int));
    b[0] = 1;

}

int main(int argc, char const *argv[])
{
    int *a = malloc(4 * sizeof(int));
    printf("%d\n", a[0] );
    test(a);
    printf("%d\n", a[0] );
    free(a);
    return 0;
}

Output:

 $ ./a.out 
    0
    0
    free(): double free detected in tcache 2
    Aborted (core dumped)
harry
  • 970
  • 6
  • 25
  • 2
    `b` is a local variable in the function. Setting it does not set `a` in the caller. So `a` is freed by both the `realloc` and the `free` call. – kaylum Aug 04 '21 at 11:34
  • 1
    https://stackoverflow.com/questions/59916332/how-to-dynamically-allocate-memory-in-a-function – Retired Ninja Aug 04 '21 at 11:34

0 Answers0