为什么你自由/删除返回一个对象,但你不能自由/删除通过参数输入的对象呢? [英] Why can you free/delete an object that was returned, but you can't free/delete an object that was entered through a parameter?

查看:96
本文介绍了为什么你自由/删除返回一个对象,但你不能自由/删除通过参数输入的对象呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,

 为int * createArray(无效)
{
     为int * ARR =(INT *)malloc的(3 * sizeof的(INT));
     ARR [0] = 69;改编[1] = 69; ARR [2];
     返回ARR;
}诠释的main()
{
    为int * myArray的= createArray();
    免费myArray的;
    返回0;
}

将释放阵列的所有内存 {69,69,69} 在由 myArray的,但

 无效freeArray为(int * A)
{
     免费A;
}诠释的main()
{
    为int * myArray的=(INT *)malloc的(3 * sizeof的(INT));
    myArray的[0] = 69;改编[1] = 69; ARR [2] = 69;
    freeArray(myarray的);
    返回0;
}

也不会做。这混淆我的原因是因为在这两种情况下,你正在处理的原始指针的副本,但删除指向的从该副本对象只适用于第一种情况。这似乎是一个矛盾,但也许我错了一个完全。有人可以清除此为我?


解决方案

  

不会做。


你为什么这样认为?

也许吧,因为毕竟 freeArray(myarray的); ,您可以访问相同的,对不对?

嗯,这是未定义行为。

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

 免费myArray的;

 免费(myarray的);

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

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?

解决方案

would not do the same.

Why'd you think like that?

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

Well, that is a result of undefined behaviour.

BTW, in your first snippet,

free myArray;

should be

free(myArray);

这篇关于为什么你自由/删除返回一个对象,但你不能自由/删除通过参数输入的对象呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆