0

I have a question about dynamic memory allocation in c or c++! When we want to figure out the size of an array we use sizeof function!

Furthermore,if we want to figure out the number of elements in which array has we do like this :

int a[20];
cout << sizeof(a) / sizeof(a[0]) << endl;

I was wondering if we could figure out the number and real size of memory which is allocated dynamically. I would really appreciate it if you tell me how, or introduce me to a reference.

Farhan Qasim
  • 990
  • 5
  • 18
MAA
  • 13
  • 5
  • 1
    `sizeof` is a compile-time construct and evaluated by the compiler. The compiler doesn't know how large dynamically allocated memory sections are, so `sizeof` cannot be used. – cadaniluk Feb 16 '18 at 15:58

1 Answers1

0

In your code, a[20] is statically allocated (in the stack). The memory used is always the size 20 * sizeof(int) and is freed at the end of the function.

When you allocate dynamically (in the heap) an array like this: int* a = malloc(20*sizeof(int)), it is your choice to take x amount of memory and fill it as you want. So it is your duty to increase or decrease the number of elements your data structure includes. This amount of memory is allocated until you free it (free(a)).

Anyway, the real size of the memory occupied is always the same (in our case 20*sizeof(int)).

See there for info about stack/heap, static/dynamic: Stack, Static, and Heap in C++

Umaiki
  • 354
  • 2
  • 14