14

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?

Community
  • 1
  • 1
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
  • 1
    A couple of reasons: http://stackoverflow.com/questions/11241014/malloc-or-normal-array-definition/11241096#11241096 – hmjd Aug 28 '12 at 14:47

6 Answers6

40

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.

hamstergene
  • 24,039
  • 5
  • 57
  • 72
5

You use dynamic memory when the size of your allocation is not known in advance only on runtime.

For example you ask a user to input names (lets say up to 10 names) and store them in a string array. Since you do not know how much names the user will provide (only on runtime that is) you will have to allocate the array only after you know how much to allocate so you will use dynamic allocation.

You can of course use an array of fixed sized 10 but for larger amounts this will be wasteful

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
giorashc
  • 13,691
  • 3
  • 35
  • 71
3

Use dynamic memory allocation, if you don't know exactly how much memory your program will need to allocate at compile-time.

int a[n] for example will limit your array size to n. Also, it allocated n x 4 bytes of memory whether you use it or not. This is allocated on the stack, and the variable n must be known at compile time.

int *a = (int *)malloc(n * sizeof (int)) on the other hand allocated at runtime, on the heap, and the n needs to be known only at runtime, not necessarily at compile-time.

This also ensures you allocate exactly as much memory as you really need. However, as you allocated it at runtime, the cleaning up has to be done by you using free.

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • I don't understand: Why do you say "the variable n must be known at compile time"? What if instead, while the program is running the user inputs "n"? Then it WOULDN't be known at compile time, or what is my noob confusion? I mean, "n" is the size of an array, so we cannot know how huge that array the user (if he inputs it , as I'm suggesting to consider) should be, so how to allocate it at compile time? – Santropedro Jul 06 '19 at 06:38
  • You can allocate more or less memory on the stack based on user input but you are limited by the extent of stack sizes. `malloc` and `new` would give you the ability to allocate a lot more memory, so, your `N` can be significantly bigger - but with the pain of memory management. – Anirudh Ramanathan Jul 06 '19 at 08:03
  • Thank you, I didn't even consider that possibility, that clarifies my doubt. – Santropedro Jul 06 '19 at 15:07
3

You should use dynamic memory when:

  • If you want your object to persist beyond the scope in which it was created.
  • Usually, stack sizes are limited and hence if your object occupies a lot of memory then you might run out of stack space in such cases one would usually go for dynamic memory allocation.

Note that c99 standard introduces Variable Length Arrays(VLA) in C so you need not use dynamic memory allocation just because you do not know the array dimensions before hand(unless ofcourse #2 mentioned above is the case)

It is best to avoid dynamic memory allocations as much as you can because it means explicitly managing the memory instead of the automatic mechanism provided by the language.Explicit memory management means that you are prone to make more errors, which might lead to catastrophic effects.
Having said that dynamic memory allocations cannot be avoided always and must be used when the use is imperative(two cases mentioned above).

Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

If you can program without dynamic allocation don't use it!
But a day you will be blocked, and the only way to unblock you will be to use dynamic allocation then now you can use it

JMBise
  • 680
  • 4
  • 19
1

Als made an interesting point that you should allocate memory from the heap if your object needs to persist beyond the scope in which it was created. In the code above, you don't need to allocate memory from heap at all. You can rewrite it like this:

#include <stdio.h>
int a = 17;
int main(void)
{
    int b = 18; //automatic stack memory
    int c[1]; // allocating stack memory. sizeof(int) * 1
    c[0] = 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[0], c);
    system("PAUSE");  
    return 0;
}

In fact, as part of the C99 standard (Variable-length array), you can use the [] operator to allocate dynamic space for an array on the stack just as you would normally do to create an array. You don't even need to know the size of the array at compilation time. The compiler will just adjust the esp register (for x86 machines) based on the requested allocation space and you're good to go.

Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
Imran
  • 71
  • 1
  • 1