为什么没有"memsize"字样?在C中返回使用malloc在堆中分配的内存块的大小? [英] Why isn't there a "memsize" in C which returns the size of a memory block allocated in the heap using malloc?

查看:135
本文介绍了为什么没有"memsize"字样?在C中返回使用malloc在堆中分配的内存块的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好.可以在 _msize 在Visual Studio中.

ok. It can be called anything else as in _msize in Visual Studio.

但是给定使用malloc分配的内存块,为什么在标准情况下不返回内存的大小?由于我们无法确定malloc之后的return指针指向多少内存,因此可以在需要时使用此"memsize"调用返回该信息. "memsize"将与malloc/free一样是特定于实现的

But why is it not in the standard to return the size of the memory given the memory block alloced using malloc? Since we can not tell how much memory is pointed to by the return pointer following malloc, we could use this "memsize" call to return that information should we need it. "memsize" would be implementation specific as are malloc/free

就像我不得不写一个包装器一样,有时返回以存储该大小的其他字节.

Just asking as I had to write a wrapper sometime back to store some additional bytes for the size.

推荐答案

因为C库(包括malloc)是为最小开销而设计的.像您想要的函数那样的功能将要求实现记录下分配的确切大小,而实现现在可以选择根据需要舍入"大小,以防止在realloc中实际重新分配.

Because the C library, including malloc, was designed for minimum overhead. A function like the one you want would require the implementation to record the exact size of the allocation, while implementations may now choose to "round" the size up as they please, to prevent actually reallocating in realloc.

存储大小需要每个分配额外的size_t,这对于嵌入式系统可能很重. (对于在编写C89时仍然很丰富的PDP-11和286.)

Storing the size requires an extra size_t per allocation, which may be heavy for embedded systems. (And for the PDP-11s and 286s that were still abundant when C89 was written.)

这篇关于为什么没有"memsize"字样?在C中返回使用malloc在堆中分配的内存块的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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