25
Memory management in depth. Lets discuss stacks and heaps
Memory management is process of controlling, allocating and using computer memory to optimize overall performance of system. Now this may sound a bit foggy but don't worry we will discuss it one by one.
Each time a program runs on your computer, a memory block is allocated to it by your Operating System. We call this memory block a segment. Each segment is then further divided into smaller blocks which is used to store chunks of data. Below visual representation of memory segment
Well that's where addresses comes in. In your memory segment, each block has a separate and unique address. Computer uses that address to read/write/update value stored in that block. Each time a variable is declared in your program, computer assigns a memory block to it in stack or heap depending upon the request made by user. BUT what is this stack and heap? Lets find out together.
Remember memory segment? Well turns out that your memory segment is divided into three main parts
- Stack
- Heap
- Code Block
Now lets go a bit deeper and discuss these thing more technically. Lets just say you declare a function call myFunc
. And you have declared some variables in it such as int a,b
. So your function will look something like this.
void myFunc(){
int a,b;
}
After you declare your function like this, this is how your memory segment look
Here's how you can initialize a pointer
int *ptr = new int;
BUT there is a catch. In stacks memory is deallocated automatically after we go out of scope of variable but that is not the case in heap. Heap memory should be deallocated explicitly. And that is where the keyword delete
comes in.
Here's how its done
delete ptr;
What it will do is delete everything stored on address in ptr. And assign NULL
to ptr.
That's it. This is it for today. I hope you like this article and if you do don't forget to subscribe
25