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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With