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

hgr*_*rev 0 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);

Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 5

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

也没有标准方法来检查分配的内存块“有多大”。您应该自己跟踪这一点。

如果调用malloc没有返回NULL,则意味着调用成功,并且您可以访问指定分配的字节数。