请问有没有指针Ç自动释放内存? [英] Will C automatically free memory with no pointers?

查看:92
本文介绍了请问有没有指针Ç自动释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我们在单独运行这片code的:

 的malloc(1024);

这会导致内存泄漏,或将自动Ç知道要释放的指针没有引用?

在换句话说,我能避免将其分配到一个指针?

 无效* P =的malloc(1024);
自由(对);


解决方案

在任何code你写一个动态分配的内存,你有2个的<​​em>责任的有关分配的内存的模块:(1 )的总是preserve一个指针起始地址的的内存块左右,(2)它可以的释放的时候不再需要它。释放内存达到的

如果你的新内存块分配给当前指向的内存没有现成块的指针第一的释放的块,你刚才改写的起始地址的由指针持有的内存原始块(违反的规则1以上的),你有现在失去自由的原始块的能力 - 这是你的内存泄漏

Let's say we run this piece of code in isolation:

malloc(1024);

Will this result in a memory leak, or will C automatically know to free a pointer with no references?

In other words, can I avoid having to assign it to a pointer?

void *p = malloc(1024);
free(p);

解决方案

In any code you write which dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed. Freeing the memory is up to you.

If you assign a new block of memory to a pointer that currently points to an existing block of memory without first freeing the block, you have just overwritten the starting address for the original block of memory held by the pointer (violating rule 1 above) and you have now lost the ability to free the original block -- which is your memory leak.

这篇关于请问有没有指针Ç自动释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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