For the last 4ish months, I’ve dived head first into a topic I’ve been very excited to get to that is C/C++ and managing memory. To preface this, I am by no means an expert but I do enjoy the subject and how vast it is. I spent a large portion of time wrapping my head around pointers and referenccing/derefeencing, before moving on to malloc and calloc. As I’ve started learning about memory management in C/C++ I’ve naturally had to pick up on heap versus stack, and this in itself helped a few data structures click as well as how applications use memory and memory leaks (it seems simple to call
free() when necessary but I can easily see why mistakes are made.)
To refresh; Heap is used for dynamic memory allocation (both heap and stack use/are stored in your machine’s RAM). You should consider using the heap when you’re going to be allocating a lot of memory, and allocating it a run time. As far as I understand and have learned, it’s best to use heap when you plan to keep that variable around for a long time, or alternatively for variables that need to dynamically allocate their memory (arrays y structs!)
Stacks on the other hand should be allocated at compile time and you shouldn’t allocate a lot of memory to them, stacks are only available to threads, but you can access the stack very quickly. Variables allocated on the stack should for all intents and purposes have a very short shelf life, most say anything created on the stack shouldn’t stick around after it’s been invoked.
I still have much to learn with malloc, calloc, realloc, free and my end goal is creating my own basic garbage collector to really solidify my learnings.