为什么动态分配的内存返回的大小与我实际尝试分配的大小不同

  • 本文关键字:分配 内存 返回 动态分配 c++ c
  • 更新时间 :
  • 英文 :


我想在内存中的结构后面添加一个字符串。如何检查我是否动态分配了正确的字节数?

示例:


const wchar_t* add_str = L"test string";
struct test_{
wchar_t* name;
size_t namelen;
} test;
void* ptest_void = malloc(sizeof(test) + wcslen(add_str)*sizeof(wchar_t));
// i cant dereference void*, hence, cant check sizeof(*ptest_void)
// then i try to get sizeof of a ptr which was cast to (test_*):
test_* ptest = (test_*)ptest_void;
size_t ptest_sz = sizeof(*ptest);
// ptest_sz has the size of _test struct, but without size of add_str...
free(ptest_void);

sizeof(ptest)不会告诉您ptest指向多少已分配内存。它"告诉"您变量ptest的字节大小,很可能是4或8,具体取决于您的系统。

也没有标准的方法来检查";"有多大";分配的内存块。你应该自己记录。

如果对malloc的调用没有返回NULL,则表示调用成功,并且您可以访问您告诉它要分配的字节数。

最新更新