free怎么知道要免费多少? [英] How does free know how much to free?

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

问题描述

在C编程中,你可以将任何你喜欢的指针作为参数传递给free,它如何知道要释放的分配内存的大小?每当我传递一个指向某个函数的指针时,我也必须传递大小(即一个 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 :-).

当您调用 free() 时,它只是查看额外信息以找出块有多大.

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

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

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