Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I need dynamic memory? [duplicate]

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?

like image 235
Niklas Rosencrantz Avatar asked Aug 28 '12 14:08

Niklas Rosencrantz


People also ask

When should dynamic memory be used?

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.

Why do you need dynamic memory?

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.

What happens if we dont free dynamic memory?

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.

Why is dynamic memory better than static?

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.


1 Answers

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.

like image 66
hamstergene Avatar answered Oct 18 '22 00:10

hamstergene