Search code examples
c++pointersnew-operatorheap-memory

How much memory is allocated in heap using new operator?


int main()
{
    int ptr* = new int[10];
}

I wonder if in heap is allocating 10 * 4 bytes (40), and for the pointer also is allocated 8 bytes, or the whole line allocates only 40 bytes. If for the pointer is allocated memory then 8 bytes are allocated in stack?

I am not sure but I think that for the ptr is allocated 8 bytes (IDK where), and for the block of 10 integer - 40 bytes (in heap).I just want to concretize. Thanks.


Solution

  • You meant int* ptr = new int[10];

    Space for at least 10 ints is allocated (the C++ runtime library and operating system might actually allocate more memory than this, but of course you have no portable way of observing that).

    That's 10 * sizeof(int) bytes. On common current desktop systems that is indeed 40 bytes.

    That memory has dynamic storage duration. It's assigned to an int* pointer type ptr which itself has automatic storage duration.