Question

Without any redundant theory. If I write:

int* t = new int[10]; //stack or heap is beign used?

and again

int t[10];// stack or heap is beign used?
Était-ce utile?

La solution

int* t = new int[10]; // Heap

int t[10]; // Stack

Note, as pointed out in the comments, the first example allocates memory on the heap, but a stack variable, t, is still needed to store the pointer to the allocated memory. This means that t will be destroyed when it goes out of scope, but the memory it points to (the int array) will remain in memory unless you used delete before you lost access to t.

In the second example, the array itself is stored on the stack and will be destroyed when t goes out of scope (do not use delete here).

Autres conseils

Technically, C++ has no notion of stack or heap, since those are implementation concepts. So an implmenentation is free to do whatever works. That said, usually memory obtained via new is from the heap, and non-static local variables (known as auto storage class variables) are on the stack.

new operator dynamically allocates memory and calls corresponding constructor of the object, if applicable (not applicable for primitive data types like int, char etc), malloc just dynamically allocates memory, dynamic allocation is always from the heap Static allocations are on stack So,

int* t = new int[10]; //heap

and again

int t[10];// stack 

All variables inside functions (main is also a function) are stored on stack withing function frame. When u enter a function new frame is made on stack in the following order

  • first, function arguments are pushed to stack
  • then return address is pushed to stack (push pc)
  • base pointer (computer register which is used to point to function frame) is pushed to stack, so the old base (frame) pointer of the outer frame is saved on stack. (push bp)
  • base pointer is set to point to location where stack pointer is pointing (mov bp, sp)
  • then space for local variables is reserved and computer access them via base pointer relatively

So, when you write

int var_int[5];
int* var_intptr = new int[10];

5x4 bytes (or more, whatever the machine is) are reserved for var_int.

4 bytes (varying on the machine) are reserved for var_intptr pointer to int.

So the pointer (variable containing the target's address) is placed on stack, but the sole object(s) made with operator new are located on heap.

When you exit the function, the local variables and arguments are popped out of the stack, and the reference to instantiated object might be lost, but the object isnt deleted.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top