免费不会删除分配给该指针(int数组)的内存,使用免费的两次工作,为什么? [英] free won't delete memory allocated to the pointer (int array), using free twice works, why?

查看:159
本文介绍了免费不会删除分配给该指针(int数组)的内存,使用免费的两次工作,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是出于好奇,我试图找到答案,我的previous问题毋庸置疑的,但他们似乎并不有答案。因此要求在这里,我只是写了code,其中我想分配内存为int指针(填满一个数组)和扫描int类型吧。一旦我用数组做的,我想删除分配给指针数据/存储。虽然我的code正常工作和一切,为什么我仍然能够即使免费的 ING 的指针看到int数组内的值。然而,如果我用免费的两次它抛出了一个错误(这是一个免费使用后预期)。这难道不是一件奇怪的行为?我用X code也于codechef,同样的行为,为什么?

This is out of curiosity, I tried to find answers to my doubt on previous questions but they don't seem to have answer to it. So asking here, I just wrote a code where I am trying to allocate memory to an int pointer (to fill up an array) and scan int values to it. Once I am done with the array, I want to delete the data/memory allocated to the pointer. Although my code works fine and everything, why am I still able to see values inside int array even after freeing the pointer. Whereas, if I use free twice it throws up an error (which was expected after single use of free). Isn't this an odd behavior ? I tried it on my mac using Xcode also on codechef, same behavior, why ?

int *num=(int *)malloc(n*sizeof(int));
int i;
for(i=0;i<n;i++)
{
    scanf("%d",&num[i]);        
}    

for(i=0;i<n-1;i++){
    temp = some_function(x);        
}

free(num); 

for(i=0;i<n;i++)
{
    printf("\nnum[%d]= %d\n",i,num[i]);        
}

里面NUM以上code打印值[]在理想情况下它不应该。

The above code prints values inside num[] which ideally it shouldn't.

推荐答案

这是不奇怪的,还是错。当调用免费上的指针,你只能告诉内存管理器,它可以再次重复使用的内存部分用于另一个的malloc 电话。它不会删除(这将需要额外的时间,没有任何功能)的内容。但是,你的可以的访问,因为指针仍然指向一个有效的地址。它导致的未定义行为的,但因为内存管理器可以给内存到其他片code的。

This is not odd, or wrong. When calling free on a pointer, you only tell the memory manager that it can re-use that portion of memory again for another malloc call. It won't erase the contents (this would take extra time with no function whatsoever). But, you can access it, because the pointer still points to a valid address. It leads to undefined behaviour though, because the memory manager could have given that memory to some other piece of code.

调用免费第二次会产生一个错误,因为内存管理器不知道指针不再为有效(你只是免费 D吧!)。其实,这是的未定义行为

Calling free a second time can generate an error, because the memory manager doesn't know that pointer anymore as being valid (you just freed it!). In fact, this is undefined behaviour.

这篇关于免费不会删除分配给该指针(int数组)的内存,使用免费的两次工作,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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