+ 1
Can someone describe what The stack and heap is and how its used?
7 Réponses
+ 12
The stack is where temporary stuff, like function arguments and local variables, goes. It's size is limited.
The heap is ordinary global memory assigned to your program for dynamic use. Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). The one has to use pointers to access memory on the heap.
In C++, when you use the new operator to allocate memory, this memory is allocated in the application’s heap segment.
example:
int *ptr = new int;
// ptr is assigned 4 bytes in the heap
int *array = new int[10];
// array is assigned 40 bytes in the heap
Stack vs Heap: Pros and Cons
Stack
- very fast access
- don't have to explicitly de-allocate variables
- space is managed efficiently by CPU, memory will not become fragmented
- local variables only (int, float, and bool...)
- limit on stack size (OS-dependent)
Heap
- variables can be accessed globally
- no limit on memory size
- (relatively) slower access
- no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
+ 9
@Aklex aghh thanks to my old resources then for that mistake, i will delete that part
Thank you for your information 😊
+ 8
no need ☺ i hope it helped you
+ 4
@Jihad Naji That's okay! Many people do not know smart pointers exist, but they are one the best modern c++ features
+ 3
@Jihad Naji You do not have to manage heap memory manually anymore with modern c++
+ 1
Thank you for the in depth explanation
0
but please also notice that on big data is fundamental to dont have just on stack, mainly for games, so you can dealloc manually the contents that you want to free the memory... this gives you full control of what is happening...