如何获得指针指向的内存大小? [英] How to get the size of memory pointed by a pointer?
问题描述
我目前正在NUMA机器上工作.我正在使用numa_free
释放分配的内存.但是,与free
不同,numa_free
需要知道要释放多少字节.有没有办法知道一个指针所指向的字节数却没有找到它?
I am currently working on a NUMA machine. I am using numa_free
to free my allocated memory. However, unlike free
, numa_free
needs to know how many bytes are to be freed. Is there any way to know that how many bytes are pointed to by a pointer without tracing it out?
推荐答案
无法使用基础API获取内存大小.在分配某处时,您必须记住大小.例如,您可以编写自己的分配器,该分配器分配4个额外的字节,存储在缓冲区的前4个字节中,在释放期间,您可以从中读取缓冲区的大小:
There is no way to obtain memory size using underlying API. You must remember size during the allocation somewhere. For Example, You may write your own allocator, that allocates 4 extra bytes, stores in first 4 bytes size of buffer, and during deallocation you can read size of buffer from it:
void *my_alloc(size_t size)
{
void *buff = numa_alloc_local( size + sizeof(size_t) );
if (buff == 0) return 0;
*(size_t *)buff = size;
return buff + sizeof(size_t);
}
void my_free(void *buf)
{
numa_free(buf - sizeof(size_t), *(size_t *)(buf - sizeof(size_t)));
}
这篇关于如何获得指针指向的内存大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!