【问题标题】:Why dynamically allocated memory return different size that i actually tried to allocate? [duplicate]为什么动态分配的内存返回我实际尝试分配的不同大小? [复制]
【发布时间】: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++ 项目中:)

标签: c++ c


【解决方案1】:

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

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

如果对malloc 的调用未返回NULL,则表示调用成功,您可以访问您告诉它分配的尽可能多的字节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2023-03-07
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多