THZ*_*THZ 2 c malloc function realloc
以下面的代码为例:
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);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,拨打电话后reallocSomething,point返回的地址是否仍然相同allocSomething?例如,如果point具有address 0x01,则当该指针由重新分配时reallocSomething,该地址是否仍然0x01?
从手册页进行realloc:
Run Code Online (Sandbox Code Playgroud)void *realloc(void *ptr, size_t size);....
realloc()返回一个指向新分配的内存的指针,该指针适合于任何类型的变量,并且可以与ptr不同,如果请求失败,则可以为 NULL。如果size等于0,则返回NULL或适合传递给free()的指针。如果realloc()失败,则原始块保持不变。它不会被释放或移动。
由于realloc可能会将分配的内存移动到新位置,因此您需要考虑这一点。