C 设置一个指向另一个指针的指针并释放

标签 c pointers

如果我调用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/

相关文章:

c - 数据类型* <变量名> 和。数据类型 *<变量名>

c++ - C++调试中的指针

c - 从不兼容的指针类型赋值[默认启用]

c - 教程中的按位运算困惑

C 数组初始化大小(以字节为单位)

c - 链接列表和指针语法错误

c - C 中的指针问题,找不到我的错误

c - APUE 对 linux 线程的描述有误吗?

无法更新指针值

仅将 float 计算为 2 位数字(不将小数点后 6 位数字格式化/四舍五入为 2)