如果我调用free(ptr)
,p1也会被释放吗?
int* some_function(){
int *p1 = malloc(sizeof(int)*10);
int *p2 = p1;
return p2;
}
int main(){
int *ptr = some_function();
free(ptr);
return 0;
}
最佳答案
当你这样做时
int *p1 = malloc(sizeof(int)*10);
你有类似的东西
+----+ +---------------------------------+ | p1 | --> | Memory enough for 10 int values | +----+ +---------------------------------+
Then when you do
int *p2 = p1;
你有类似的东西
+----+ | p1 | --\ +----+ \ +---------------------------------+ >--> | Memory enough for 10 int values | +----+ / +---------------------------------+ | p2 | --/ +----+
That is, you have two pointers pointing to the very same memory.
When you return p2
you simply copy the pointer, much like what happens when you initialize p2
, and inside the main
function you have
int *ptr = some_function();
这会导致
+-----+ +---------------------------------+ | ptr | --> | Memory enough for 10 int values | +-----+ +---------------------------------+
这是不同的变量,但它们的内容都是相同的,并且都是初始malloc
调用返回的指针。
关于C 设置一个指向另一个指针的指针并释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49632563/