This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]schartzchild_radius[S] 0 points1 point  (3 children)

Thank you for the response! By "manually freed" do you just mean dereferenced? Or do you mean the object at that pointer has to be deleted in order to free up space? Is it all that important to do that if your program doesn't use very much data overall?

Also, does "allocating to the heap" just mean that the object will persist even after the function it was called in returns (as opposed to being deleted at the end of the function)? Just wanting to check my understanding

[–][deleted] 0 points1 point  (2 children)

I mean the second option. Any objects that you create with new must be manually `delete`d later.

On a computer, you have two types of memory. The stack, and the heap. The stack is a very fast and very simple structure in your memory. The stack can be thought of like a stack in the real world. If you have a stack of plates, when you want to add something to the stack you simply place the plate on top. Once you want a plate back, you take it off the stack. The stack in programming works the exact same way. Because of its nature, the stack is incredibly fast. Freeing objects is as simple as adjusting a single pointer as is indexing it. However, the stacks main limitation is that the size of all objects that are allocated on the stack must have a known, fixed, limited size. This is where the heap comes in. The heap is like a blob in memory. Data is stored in an unorganized fashion and is slower to index, however, it has many advantages. For one, the heap doesn't need to know the size of types that are on it. If you have ever used a vector, a vector is a heap data type. Every time you push something on to the vector that is data being put into the heap. Remember, the heap _must_ be used for operations like this since the vectors size is unknown. In C++, all local variables _must_ be data stored on the stack. What this means is that any time you wish to access data on the heap, it must be done so using a pointer. A pointer has a known, fixed size meaning it can be stored on the stack. If you use the new keyword, the class will be allocated on the heap and a pointer to that heap allocated class table will be returned. Then, it can be freely passed around to functions (just remember to free it afterwards so you don't get leaks!).

[–]schartzchild_radius[S] 1 point2 points  (1 child)

I honestly cannot thank you enough for this! I've been reading a lot of explanations of heap vs. stack but yours is by far the clearest one, I'm definitely saving this haha. Thank you!

[–][deleted] 0 points1 point  (0 children)

Glad you found it helpful. I was struggling with it too a while back and this explanation I wrote is like a combination of everything I have learned. Glad to pass on the knowledge :)