Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what will realloc do to the old pointer [duplicate]

I have a question about the realloc function. Will the content of old pointer be changed after apply realloc function? The code is

main () {
    int *a, *b, i;

    a = calloc(5, sizeof(int));
    for (i = 0; i < 5; i++)
            a[i] = 1;
    for (i = 0; i < 5; i++)
            printf("%d", a[i]);
    printf("\n%p\n", a);

    b = realloc(a, 200000 * sizeof(int));
    if(b == NULL)
            printf("error\n");
    for (i = 0; i < 5; i++)
            printf("%d", a[i]);
    printf("\n");
    for (i = 0; i < 10; i++)
            printf("%d", b[i]);

    printf("\n%p %p\n", a, b);
}

The output is

11111
0x2558010
00111
1111100000
0x2558010 0x7f29627e6010

Pointer a still point to the same address, but the content is changed.

like image 640
Shuai Xu Avatar asked Dec 07 '22 22:12

Shuai Xu


1 Answers

Pointer a still point to the same address, but the content is changed.

That's because realloc() may first try to increase the size of the block that a points to. However, it can instead allocate a new block, copy the data (or as much of the data as will fit) to the new block, and free the old block. You really shouldn't use a after calling b = realloc(a, 200000 * sizeof(int)) since the realloc call may move the block to a new location, leaving a pointing to memory that is no longer allocated. Use b instead.

like image 129
Caleb Avatar answered Jan 01 '23 14:01

Caleb