C-free()不会释放整个数组 [英] C - free() is not freeing the entire array

查看:68
本文介绍了C-free()不会释放整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指向int的指针,在我调用free之后,我看到只有前两个元素被释放了,其余的保持不变.有人可以解释吗?

I have a pointer to int, and after I call free, I see that only the first two elements get freed, the rest remain the same. Can anybody explain?

int main() {
        int* a = (int*)malloc(10*sizeof(int));

        a[0] = 12;
        a[1] = 15;
        a[2] = 100;
        a[3] = 101;
        a[4] = 102;
        a[5] = 103;
        a[6] = 109;
        a[7] = 999;

        printf("%d %d %d %d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);

        free(a);
        printf("Done freeing.\n");
        printf("%d %d %d %d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);

        return 0;
}

输出:(很抱歉,将所有输出都放在一行中)

Output: (sorry for putting all the output in one line)

12 15 100 101 102 103 109 999完成释放.0 0 100 101 102 103 109 999

12 15 100 101 102 103 109 999 Done freeing. 0 0 100 101 102 103 109 999

推荐答案

当您调用 free 时,您只是在告诉操作系统您已经完成了该内存块的操作.您保证不再使用它.如果您违背了诺言,那就是您的问题.

When you invoke free, you're just telling the OS that you're done with that memory chunk. You promise not to use it again. If you break that promise, that's your problem.

重要的旁注:

调用 if(ptr) if(NULL!= ptr)不会测试 ptr 是否指向已分配的内存块.它仅测试它是否指向任何东西.调用 free 不会将null分配给任何指针.您必须手动进行处理.我是很难学到的……

Invoking if(ptr) or if(NULL != ptr) does NOT test if ptr points at an allocated memory chunk. It only tests whether it points at anything at all. Invoking free does NOT assign null to any pointers. You have to take care of that manually. I learned this lesson the hard way...

重要的旁注2:

没有通用的方法来确定是否分配了 ptr 指向的内存.某些平台提供了此功能,但并非全部.

There's no general way to find out whether the memory ptr points at is allocated or not. Some platforms offer this feature, but not all.

现在,也许您想知道,如果 free(ptr)为ptr分配NULL会更好吗?也许吧,也许不是.不利的一面是它是错误的安全性.考虑以下代码:

Now, maybe you wonder, wouldn't it be better if free(ptr) assigned NULL to ptr? Maybe, maybe not. The downside would be that it's false safety. Consider this code:

int *p1=malloc(sizeof *p1);
int *p2=p1;
free(p1);

您期望p2具有什么价值?最好了解指针实际上是否为NULL.

What value do you expect p2 to have? It's better to learn what it actually means that a pointer is/isn't NULL.

这篇关于C-free()不会释放整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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