Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does realloc change pointer address?

Take this code for example:

Struct* allocSomething(void) {
    int n; 
    Struct *something = malloc(n*sizeof(Struct));
    return something;
}

Struct* reallocSomething(Struct **s) {
    int n;
    Struct *something = realloc(*s, (n*sizeof(int)) - 1 * sizeof(Struct));
    return something;
}

int main() {
    Struct *point = allocSomething();
    //code does something...
    point = reallocSomething();
    free(point);
}

My question is, after calling reallocSomething, point has still the same address returned by allocSomething? For example, if point have address 0x01, when this pointer get reallocated by reallocSomething, is that address still 0x01?

like image 629
THZ Avatar asked Oct 14 '25 11:10

THZ


1 Answers

From the man page for realloc:

void *realloc(void *ptr, size_t size);

....

realloc() returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails. If size was equal to 0, either NULL or a pointer suitable to be passed to free() is returned. If realloc() fails the original block is left untouched; it is not freed or moved.

Since realloc may move the allocated memory to a new location, you need to account for this.

like image 134
dbush Avatar answered Oct 17 '25 01:10

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!