简体   繁体   中英

Why won't realloc work

I have this problem in a bigger project, in which for some reason the realloc function does absolutely nothing. Am I missing something obvious?

Here is a simplified example:

#include <stdio.h>
#include <string.h>

int main()
{
    int x = 1, y = 2, z = 3;
    int* arr, *arr1;
    int** arra;

    arra = (int**)malloc(sizeof(int*));
    arr = (int*)malloc(sizeof(int));
    arr[0] = x;
    arra[0] = arr;
    arra = (int*)realloc(arra, sizeof(int*) + sizeof(int*));
    arr1 = (int*)malloc(sizeof(int));
    arr1[0] = y;
    arra[1] = arr1;

}

When I debugged, the final arra was {{1}} , even though to my understanding it should be {{1},{2}} .

The debugger does not know that arra is any more than a single pointer. If you want the debugger to print out the contents of arra as an array, you need to walk the elements yourself, or cast it to an array type before printing.

First of all, how do you know that realloc has done nothing? Returning a different pointer is not warranted by realloc(3) , as if possible it will try the realloc in place. Having said this, there's no way to know (externally to malloc) that it has done whatever you like or not, as the return value (being the same pointer) gives you no information about the new size.

By the way, how did you check if the sizes where the same or not. You don't show how you did in your code. Indeed, from your code you cannot get any information of the actual size returned by realloc (just see if the program crashed at all or not) If your used the sizeof operator, you are wrong, as you are using it with pointers and the size returned is always the same (the size of a pointer variable, an address) if you used the debugger, it has the same resources as the main program to check the size of whatever realloc returned (that is, nothing again) so, what is the reasoning to conclude that realloc is not working.

Next time, do several mallocs (not only two) and realloc all pointers to values much greater (to avoid optimizations leading to the same pointer returned) like this:

char *a = malloc(10), *b = malloc(10), *c = malloc(10);
char *aa = realloc(a, 10000), *bb = realloc(b, 10000), *cc = realloc(c, 10000);
if (a != aa || b != bb || c != cc) 
    printf("realloc *changed* the return values "
           "(a=%p, aa=%p, b=%p, bb=%p, c=%p, cc=%p)\n", 
             a,    aa,    b,    bb,    c,    cc);
else
    printf("realloc didn't move the return values\n");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM