-1

Allocating memory for different sizes. But sizeof pointers are same. Whats the difference?

    short * v = (short*)malloc(sizeof(short));
    std::cout <<"....adress.."<< sizeof(&v) <<endl;

    v=(short*)malloc(sizeof(short)*999);
    std::cout <<"....adress.."<< sizeof(&v) <<endl;

result is 8 for both. I expected 999*8 , how can I allocate 999 * 8 in memory?

0___________
  • 60,014
  • 4
  • 34
  • 74
hipativ414
  • 19
  • 5
  • `sizeof` runs at compile time and I think you are just seeing the size of the pointer. See https://stackoverflow.com/questions/2615203/is-sizeof-in-c-evaluated-at-compilation-time-or-run-time – mlibby Jun 25 '20 at 19:19
  • 1
    Does this answer your question? [Is sizeof in C++ evaluated at compilation time or run time?](https://stackoverflow.com/questions/2615203/is-sizeof-in-c-evaluated-at-compilation-time-or-run-time) – mlibby Jun 25 '20 at 19:20
  • 1
    Since `sizeof` is executed at compile time, `sizeof (&v)` is equivalent of `sizeof (short**)`. – Algirdas Preidžius Jun 25 '20 at 19:20
  • All of this means is that your program is responsible for remembering how much you allocated, which is why programs that allocate memory and use raw pointers are hard to maintain. There is no `sizeof` trick you can use that will give you this information. – PaulMcKenzie Jun 25 '20 at 19:22
  • struct mystruct { char s[1]; }; i can see sizeof struct btw before malloc – hipativ414 Jun 25 '20 at 20:11

2 Answers2

3

sizeof(&v) is - since &v is a pointer - the size of a pointer. This is constantly 8 on a 64 bit machine (regardless of the size of allocated memory to which this pointer points).

BTW: The C++ standard does not provide a way to find out, when only having a pointer at hand, how large the memory block to which this pointer points actually is.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

"how can I allocate 999 * 8 in memory?" You already did with the line

v=(short*)malloc(sizeof(short)*999);

v is now holding a pointer to a memory location that can store 999 shorts.

stackoverblown
  • 734
  • 5
  • 10