-2

I am getting a weird result with these 2 simple lines

char* reverse = (char*) malloc(sizeof(char)*19);
cout << sizeof(reverse)/sizeof(char) << endl;

No matter what number i put in the first line (in this example, it is 19). I always get 4 as the output. What is wrong ? Thanks.

cuongptnk
  • 472
  • 3
  • 15

1 Answers1

3

On 32-bit machine sizeof pointer is 32 bits (4 bytes), while on 64 bit machine it's 8 bytes. Regardless of what data type they are pointing to, they have fixed size.

And

sizeof(char) = 1 byte

So, you are getting 4 every time because your system is a 32-bit machine.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • 2
    Your answer would be even better if you explained how to do what the OP was trying to do. – Carey Gregory Dec 29 '16 at 05:09
  • I think there is no way to recalculate the size – cuongptnk Dec 29 '16 at 05:21
  • http://stackoverflow.com/questions/10639666/how-to-determine-the-size-of-an-allocated-c-buffer – cuongptnk Dec 29 '16 at 05:21
  • I agree with both of you. I answered why OP is getting 4 every time and i guess there is no straight forward approach to get the actual size from the pointer (not 100% sure though). If anyone knows that, you can tell me how to do that or you can edit my answer. Thanks :) – Wasi Ahmad Dec 29 '16 at 05:25