Search code examples
cmemorymemory-managementmallocdynamic-memory-allocation

How do I free up memory allocated implicitly in an array?


For dynamic memory allocation in C, you have deallocate (or free) the reserved memory before you can execute and compile your program. For example:

....
... = malloc(...)
...
free(...)
return 0;

But how does it work if I don't use dynamic memory allocation. For example, if I reserve 40000000 bytes of space using int array [10000000], how can I free up the memory later on in the program when I don't need it?


Solution

  • There are different ways to allocate memory in C.

    • Automatic storage duration (a.k.a. local variables) - allocated automatically when a block is entered (a function, if statement, loop, or whatever), and deallocated when the block is exited.
    • Static storage duration (a.k.a. global variables and static local variables) - allocated automatically at the beginning of the program, and deallocated automatically at the end.
    • Dynamic storage duration (a.k.a. the heap) - allocated with malloc and deallocated with free.

    By the way, you don't have to deallocate everything before exiting the program. The operating system will deallocate all memory belonging to your program when it exits. (Otherwise you'd have to restart your computer a lot more often)