简体   繁体   中英

What happens when using realloc and memory is written to a new address?

Let's say I have a function which accepts a pointer to a struct, which is defined like so

typedef struct Array {
    int capacity;
    int size;
    void **items;
} Array;

This function will realloc the memory of array->items to increase the size.

The function is given below

void doubleArray(Array *array) {
    array->capacity *= 2;
    void **items = realloc(array->items, array->capacity);
    if(items == NULL) {
        exit(1);
    }
    array->items = items;
}

What I am have difficulty understanding is, if I assign void **items to the result of realloc, and realloc returns a new memory address because the previous buffer has been overwritten , does array->items get assigned correctly to the new value even after returning from the function?

Or will the fact that void **items is defined within the local scope of the function doubleArray mean that array->items becomes a dangling pointer because it is not correctly re-assigned because the reference to void **items is deleted once the function exits?

Your problem of understanding is not about realloc() , its's about pointer and local variable in general.

does array->items get assigned correctly to the new value even after returning from the function?

In your code above, it is correctly assigned. Although pointer points to some address, pointer itself is an ordinary variable.

array->items becomes a dangling pointer because it is not correctly re-assigned because the reference to void **items is deleted once the function exits?

No. No pointer is deleted. Local variable void **items itself is out of scope, but not what it points to.

Consider:

void foo(Array *a) {
    int sz = 23;
    a->size = sz;
}

Will a->size become "dangling" after the function return ? Your problem is the same as this one.

The first thing that you should note is, the expression:

void **items = realloc(array->items, array->capacity);

should probably be changed to:

void **items = realloc(array->items, (array->capacity) * sizeof(void *));

Secondly, to answer your question:

does array->items get assigned correctly to the new value even after returning from the function?

Its does, because you pass a pointer (to a structure) to your function, thus the function has the ability to modify the struct member items .

Next, when you assign array->items = items; and the function returns, the local variable items runs out of scope, but remember, its value which have been assigned to array->items , is the address of memory that has allocated storage duration, so array->items is not a dangling pointer because it is pointing to valid memory.

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