如何免费知道多少自由? [英] How does free know how much to free?

查看:98
本文介绍了如何免费知道多少自由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言编程,你可以通过任何你喜欢的释放参数样的指针,它如何知道所分配的内存的大小来释放?每当我一个指针传递给一些功能,我也必须传递的大小(即10个元素的数组需要接收10作为参数知道数组的大小),但我没有大小传递给免费功能。不为什么,我可以使用同样的技术在我自己的功能,节省了我从需要到购物车周围的数组的长度的额外的变量?

In C programming, you can pass any kind of pointer you like as an argument to free, how does it know the size of the allocated memory to free? Whenever I pass a pointer to some function, I have to also pass the size (ie an array of 10 elements needs to receive 10 as a parameter to know the size of the array), but I do not have to pass the size to the free function. Why not, and can I use this same technique in my own functions to save me from needing to cart around the extra variable of the array's length?

推荐答案

当你调用的malloc(),你指定的内存分配量。实际使用的内存量超过此略多,包括额外的信息的记录(至少)块多大。你不能(可靠)的访问,其他的信息 - 而也不应该知道: - )

When you call malloc(), you specify the amount of memory to allocate. The amount of memory actually used is slightly more than this, and includes extra information that records (at least) how big the block is. You can't (reliably) access that other information - and nor should you :-).

当你调用免费(),它只是着眼于额外的信息,找出块有多大。

When you call free(), it simply looks at the extra information to find out how big the block is.

这篇关于如何免费知道多少自由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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