c++ - 尝试读取 sizeof() 返回意外结果

标签 c++ pointers memory memory-management heap-memory

这是我的代码。正如您可能知道的那样,我是 C++ 的初学者,尤其是指针。我边做边学,这就是为什么我有这些 Log() 输出,只是帮助我看看我是否正确地完成了所有操作。我遇到了一个读取变量/数据类型大小的函数,这让我有点困惑。

如果我故意在堆上分配 8 个字节的内存给变量“buffer”,为什么 sizeof() 将“buffer”读取为 4 个字节?我在这里错过了什么/做错了/不理解什么?

#include <iostream>

#define Log(message) std::cout << message << std::endl;

int main()
{
char* buffer = new char[8];
Log(sizeof(buffer));

for (int i = 0; i < 8; i++)
{
    *buffer = 10;
    Log("Buffer is a variable that takes up 8 bytes of memory and is located on the heap. It holds 
    the value " << ((std::string*)*buffer) << " located at the memory address " << 
    ((std::string*)&buffer));
}

system("pause");
}

最佳答案

sizeof(x) 告诉您 x 的大小,而不是 x 指向的任何内容的大小。

在一个不相关的注释中,x 没有安装到 std::string,因此强制转换是错误的。

建议:忘记new[],只使用std::string buffer。它将为您管理 new[]delete[],当您复制它、添加字符等时也是如此。

关于c++ - 尝试读取 sizeof() 返回意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66597206/

相关文章:

c++ - 在 Qt pro 文件中定义 bool

string - 为什么 &str 原语存在?

c++ - SDL_Init 中的大内存泄漏

C++/OpenCV : How to use BOWImgDescriptorExtractor to determine which clusters relate to which images in the vocabulary?

c++ - 从函数指针输出动态数组

c - 即时调整 char* 的大小 - 为什么此代码*有效*?

ios - NSZombie 的替代品

linux - `--oom-kill-disable` 对 Docker 容器有什么作用?

c++ - 想知道 c++ 中的内存部分是如何工作的

c++ - 如何访问 C++ 中的私有(private)嵌套类?