【发布时间】:2012-10-19 13:50:21
【问题描述】:
可能重复:
Any function to query the size of an allocated block?
Getting the size of a malloc only with the returned pointer
假设我让用户使用 malloc 函数指定要传递给 int *x 的字节数。有没有办法确定分配给整数的实际字节数?
【问题讨论】:
可能重复:
Any function to query the size of an allocated block?
Getting the size of a malloc only with the returned pointer
假设我让用户使用 malloc 函数指定要传递给 int *x 的字节数。有没有办法确定分配给整数的实际字节数?
【问题讨论】:
没有便携的方式。语言标准没有提供任何方法来做到这一点。
每个实现都需要以某种方式跟踪malloced 内存的大小,以便能够正确地free 它,因此它可能提供一种获取该信息的方法。在glibc的malloc.h中,有一个原型
size_t malloc_usable_size(void *);
这允许您获取为传入指针分配的可用字节数,但这通常大于malloc 调用中请求的字节数。其他实现可能会提供其他方法来获取此类信息。
【讨论】: