Trying to read sizeof() returns unexpected result

Viewed 60

This is my code. As you can probably tell, I am a complete beginner to C++ and especially pointers. I learn by doing, that's why I have those Log() outputs, just helps me see if I am doing everything correctly. I came across a function that reads the size of the variable/datatype, and it kind of confused me here.

If I purposely allocate 8 bytes of memory on the heap to the variable 'buffer', why does sizeof() read 'buffer' as 4 bytes? What am I missing/doing wrong/not understanding here?

#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");
}
2 Answers

sizeof(x) tells you the size of x, not the size of whatever x points to.

On an unrelated note, x does not mount to a std::string so the cast is wrong.

Suggestion: forget about new[], just use std::string buffer. It will manage new[] and delete[] for you, also when you copy it, add characters, etcetera.

buffer is a pointer object. It points to the first element of a char[8] object (that has no name), but it itself is a char *. On your platform, all pointers occupy 4 bytes. On other common platforms, all pointers occupy 8 bytes.

Note that your program has undefined behaviour because you reinterpret *buffer as std::string*. A char is totally unrelated to std::string*.

Related