Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are pointers in C++ stored, on the stack or in the heap?

I am trying to understand the difference between the stack and heap memory, and this question on SO as well as this explanation did a pretty good job explaining the basics.

In the second explanation however, I came across an example to which I have a specific question, the example is this:

heap allocation example

It is explained that the object m is allocated on the heap, I am just wondering if this is the full story. According to my understanding, the object itself indeed is allocated on the heap as the new keyword has been used for its instantiation.

However, isn't it that the pointer to object m is on the same time allocated on the stack? Otherwise, how would the object itself, which of course is sitting in the heap be accessed. I feel like for the sake of completeness, this should have been mentioned in this tutorial, leaving it out causes a bit of confusion to me, so I hope someone can clear this up and tell me that I am right with my understanding that this example should have basically two statements that would have to say:

1. a pointer to object m has been allocated on the stack

2. the object m itself (so the data that it carries, as well as access to its methods) has been allocated on the heap

like image 815
nburk Avatar asked Jun 24 '14 07:06

nburk


People also ask

Are pointers stored in stack or heap in C?

Pointer is allocated on the stack and the object it is pointing to is allocated on the heap.

Are all pointers stored in heap?

Pointers can be stored on the stack, the heap, or be statically allocated. The objects they point to can be stored on the stack, the heap, or statically as well.

Where are pointers located in memory in C?

To answer your question: ptr is stored at stack.

Why pointer are stored in stack?

A stack is a specialized buffer that is used by a program's functions to store data such as parameters, local variables and other function-related information. The stack pointer -- also referred to as the extended stack pointer (ESP) -- ensures that the program always adds data to the right location in the stack.


1 Answers

Your understanding may be correct, but the statements are wrong:

A pointer to object m has been allocated on the stack.

m is the pointer. It is on the stack. Perhaps you meant pointer to a Member object.

The object m itself (the data that it carries, as well as access to its methods) has been allocated on the heap.

Correct would be to say the object pointed by m is created on the heap

In general, any function/method local object and function parameters are created on the stack. Since m is a function local object, it is on the stack, but the object pointed to by m is on the heap.

like image 132
Rakib Avatar answered Oct 08 '22 22:10

Rakib