Reputation: 353
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?
Upvotes: 0
Views: 156
Reputation: 123488
For dynamic memory allocation in C, you have deallocate (or free) the reserved memory before you can execute and compile your program.
That's...confused. Dynamic memory only exists at runtime - it has nothing to do with compiling or executing the program. You free
memory when you don't need it anymore in the running program.
As for things not allocated using *alloc
...
If you define int array[10000000];
within the body of a function and without the static
keyword, then array
has automatic storage duration; the memory for it is reserved when you enter the function and released when you exit1, 2. If you define the array at file scope, outside the body of any function, or if you declare it with the static
keyword, then array
has static storage duration and memory will be reserved for it when the program starts and released when the program exits.
for
loop, then the memory is only guaranteed to be available for the duration of that loop. However, as a practical matter, most compilers will allocate space for all locals at function entry and release it on function exit.
Upvotes: 1
Reputation: 7490
There's a reason if it is called dynamic memory: it can be dynamically allocated/deallocated whenever you need it.
And there's a reason also if the opposite of dynamic memory is something... that's not dynamic: a static array like the one you mentioned cannot be deallocated.
What you need is the concept of lifetime of a variable:
int array [10000000]
is a global variable, it's lifetime is the whole life of the programint array [10000000]
is within a block enclosed by curly braces { }
, it is stored in the stack and it's life ends as soon as the execution exits the blockstatic
keyword (static int array [10000000];
) its lifetime is the whole program life as well though its scope is limited to the blockUpvotes: 1
Reputation: 58888
There are different ways to allocate memory in C.
if
statement, loop, or whatever), and deallocated when the block is exited.static
local variables) - allocated automatically at the beginning of the program, and deallocated automatically at the end.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)
Upvotes: 1