Dynamic memory allocation

is it necessery to delete the memory of dynamic allocated after the written code is done??

The memory you allocate in a program is then reserved for you. You can do what you like with this block of memory. The allocated memory is located on the heap, it can be accessed from anywhere. The whole program can work with it while it is running.

So you are free to use the memory you allocated until the program you wrote exits. There is no way for the computer to know during execution that this particular block of allocated memory will never be used again. For what the runtime environment knows, you reserved the memory, so you can use it whenever you like.

But now assume you allocated a lot of memory because you needed it for a short period of time, but your program is supposed to run for a long time. And it might do the same thing again, allocating a lot of memory again. Every time you do this, you eat up more and more RAM, although you don’t need it. This is called a memory leak.

That’s why, after you’re done using the allocated memory, you have to free it. Then the program explicitly states “I will never use the data I stored there again, I do not want this memory to be reserved any longer”. So the next time you need more memory, the same region can be reserved again. Or it could even be used by another program.

In case of any doubt feel free to ask :slight_smile:
mark your doubt as resolved if you got the answer