【发布时间】:2022-08-18 20:07:22
【问题描述】:
我想在内存中的结构之后添加一个字符串。 如何检查我是否动态分配了正确数量的字节?
例子:
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(pointer)返回指针的大小,而不是它指向的内容。 -
这是一个错字,我编辑了现在有 sizeof(*ptest) 的问题
-
这段代码也应该是 C 或 C++?它的外观应该有所不同。
-
不要在 C++ 中使用
malloc/free。如果你使用new/new[]/delete/delete[]必须,但一般尽量避免手动内存管理。首先使用容器,如果必须使用智能指针,几乎从不使用原始手动内存管理。 -
我有 C API(具体来说是 Windows ETW),我在 C++ 项目中:)