为什么可以释放/删除返回的对象,但是不能释放/删除通过参数输入的对象?

时间:2021-06-11 21:20:06

From what I understand,

据我所知,

int * createArray ( void )
{
     int * arr = (int*)malloc(3*sizeof(int));
     arr[0] = 69; arr[1] = 69; arr[2]; 
     return arr;
}

int main ()
{
    int * myArray = createArray();
    free myArray;
    return 0;
}

would free all the memory of the array {69, 69, 69} at the memory address pointed by myArray, but

将释放数组{69,69,69}的所有内存放在myArray指向的内存地址处,但是

void freeArray ( int * A )
{
     free A;
}

int main ()
{
    int * myArray = (int*)malloc(3*sizeof(int));
    myArray[0] = 69; arr[1] = 69; arr[2] = 69; 
    freeArray(myArray);
    return 0;
}

would not do the same. The reason that this confuses me is because in both cases you are dealing with a copy of the original pointer, but deleting the pointed-to object from that copy only works in the first case. This seems like an inconsistency, but maybe I'm wrong an entirely. Can someone clear this up for me?

不会做同样的事情。这让我感到困惑的原因是因为在这两种情况下你都在处理原始指针的副本,但是从该副本中删除指向的对象仅适用于第一种情况。这似乎是一种不一致,但也许我完全错了。有人可以为我清除这个吗?

2 个解决方案

#1


would not do the same.

不会做同样的事情。

Why'd you think like that?

你为什么这么想?

Maybe, because, after freeArray(myArray);, you are able to access the same, right?

也许,因为,在freeArray(myArray);之后,你能够访问同样的,对吧?

Well, that is a result of undefined behaviour.

嗯,这是未定义行为的结果。

BTW, in your first snippet,

顺便说一句,在你的第一个片段中,

free myArray;

should be

free(myArray);

#2


From what I understand, [X] would free all the memory of the array {69, 69, 69} at the memory address myArray

根据我的理解,[X]将释放数组{69,69,69}的所有内存在内存地址myArray

Right.

but [Y] would not do the same.

但[Y]也不会这样做。

Wrong.

Your understanding is incorrect. Please indicate where you read that, so that we may endeavour to correct this egregious error at source.

你的理解是不正确的。请说明您的阅读地点,以便我们尽力在源头纠正这一严重错误。

[X] and [Y] do the same.

[X]和[Y]也这样做。

#1


would not do the same.

不会做同样的事情。

Why'd you think like that?

你为什么这么想?

Maybe, because, after freeArray(myArray);, you are able to access the same, right?

也许,因为,在freeArray(myArray);之后,你能够访问同样的,对吧?

Well, that is a result of undefined behaviour.

嗯,这是未定义行为的结果。

BTW, in your first snippet,

顺便说一句,在你的第一个片段中,

free myArray;

should be

free(myArray);

#2


From what I understand, [X] would free all the memory of the array {69, 69, 69} at the memory address myArray

根据我的理解,[X]将释放数组{69,69,69}的所有内存在内存地址myArray

Right.

but [Y] would not do the same.

但[Y]也不会这样做。

Wrong.

Your understanding is incorrect. Please indicate where you read that, so that we may endeavour to correct this egregious error at source.

你的理解是不正确的。请说明您的阅读地点,以便我们尽力在源头纠正这一严重错误。

[X] and [Y] do the same.

[X]和[Y]也这样做。