Possible Duplicate:
Malloc or normal array definition?
We learn that there is dynamic memory in C and dynamic variables:
#include <stdio.h>
int a = 17;
int main(void)
{
int b = 18; //automatic stack memory
int * c;
c = malloc( sizeof( int ) ); //dynamic heap memory
*c = 19;
printf("a = %d at address %x\n", a, &a);
printf("b = %d at address %x\n", b, &b);
printf("c = %d at address %x\n", *c, c);
free(c);
system("PAUSE");
return 0;
}
How do I know which type of memory to use? When do I ned one or the other?
Reasons and Advantage of allocating memory dynamically:When we do not know how much amount of memory would be needed for the program beforehand. When we want data structures without any upper limit of memory space. When you want to use your memory space more efficiently.
Dynamic memory allocation is a process that allows us to do exactly what we're looking to do above, to allocate memory while our program is running, as opposed to telling the computer exactly how much we'll need (and for what) ahead of time.
If dynamically allocated memory is not freed, it results in a memory leak and system will run out of memory. This can lead to program crashing.
Dynamic memory allocation is preferred in the linked list. It saves running time as it is fast. It is slower than static memory allocation. Static memory allocation allots memory from the stack.
Use dynamic in the following situations:
When you need a lot of memory. Typical stack size is 1 MB, so anything bigger than 50-100KB should better be dynamically allocated, or you're risking crash. Some platforms can have this limit even lower.
When the memory must live after the function returns. Stack memory gets destroyed when function ends, dynamic memory is freed when you want.
When you're building a structure (like array, or graph) of size that is unknown (i.e. may get big), dynamically changes or is too hard to precalculate. Dynamic allocation allows your code to naturally request memory piece by piece at any moment and only when you need it. It is not possible to repeatedly request more and more stack space in a for
loop.
Prefer stack allocation otherwise. It is faster and can not leak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With