When do I need dynamic memory?

Niklas R. picture Niklas R. · Aug 28, 2012 · Viewed 15.5k times · Source

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?

Answer

hamstergene picture hamstergene · Aug 28, 2012

Use dynamic in the following situations:

  1. 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.

  2. When the memory must live after the function returns. Stack memory gets destroyed when function ends, dynamic memory is freed when you want.

  3. 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.