How is dynamic memory allocation better than an array?

int numbers*; numbers = malloc ( sizeof(int) * 10 ); 

I want to know how this dynamic memory is allocated, if I can only store 10 int elements in a memory block? I could just use an array and dynamically store items using an index. Why is the above approach better?

I am new to C and this is my second day and I may seem stupid, so please bear with me.

+1
source share
7 answers

In this case, you can replace 10 with a variable that is assigned at runtime. This way you can decide how much memory you need. But with arrays, you must specify an integer constant during the declaration. Thus, you cannot decide if the user will really need as many places as announced or, worse, may not be enough.

With this dynamic allocation, you can assign a larger place in memory and copy the contents of the first place to a new one to give the impression that the array has grown as needed.

This helps ensure optimal memory utilization.

+4
source

The main reason malloc() is useful is not that the size of the array can be determined at run time - modern versions of C allow this with regular arrays. There are two reasons:

  • Objects allocated using malloc() have flexible lifetimes;

That is, you gain control over the execution time, when to create the object, and when to destroy it. An array allocated using malloc() exists from the moment malloc() called until the corresponding call to free() ; on the contrary, declared arrays either exist until the function is declared in the outputs, or until the program terminates.

  • malloc() reports an error, allowing the program to process it gracefully.

If there is no allocation of requested memory, malloc() can return NULL , which allows your program to detect and process the condition. There is no such mechanism for declared arrays - if it is unable to allocate sufficient space, either the program crashes at runtime or does not load at all.

+4
source

There is a difference with where the memory is allocated. Using array syntax, memory is allocated on the stack (assuming you are in a function), while malloc'ed arrays / bytes are allocated on the heap.

 /* Allocates 4*1000 bytes on the stack (which might be a bit much depending on your system) */ int a[1000]; /* Allocates 4*1000 bytes on the heap */ int *b = malloc(1000 * sizeof(int)) 

Stack distribution is fast and often preferable if:

  • Requires a "small" amount of memory.
  • An array pointer should not be returned from a function

Heap allocation is slower, but has the following advantages:

  • Available heap memory (usually) -> than available stack memory
  • You can freely pass a pointer to allocated bytes, for example. returning it from a function - just remember to free it at some point.

The third option is to use statically initialized arrays if you have a common task that always requires a small array. Given that you can free the memory statically consumed by the array, you avoid heap memory, gain the flexibility to pass a pointer, and avoid tracking pointer ownership to free memory.

Edit: if you use C99 (by default with the gnu c compiler, I think?), You can make arrays of stacks of variable length, for example

 int a = 4; int b[a*a]; 
+3
source

In the example you specified

 int *numbers; numbers = malloc ( sizeof(int) * 10 ); 

There are no clear advantages. Although, imagine that 10 is a value that changes at runtime (for example, user input), and that you need to return this array from the function. For example.

 int *aFunction(size_t howMany, ...) { int *r = malloc(sizeof(int)*howMany); // do something, fill the array... return r; } 

malloc takes the place from the heap, and something like

 int *aFunction(size_t howMany, ...) { int r[howMany]; // do something, fill the array... // you can't return r unless you make it static, but this is in general // not good return somethingElse; } 

will consume a stack that is not as big as the whole heap.

A more complex example exists. For example. if you need to build a binary tree that grows according to some calculations performed at runtime, basically you have no choice but to use dynamic memory allocation.

+2
source

The size of the array is determined at compile time, while dynamic allocation is performed at runtime.

Thus, in your case, you can use the pointer as an array: numbers[5] .

If you don't know the size of your array when writing a program, using runtime allocation is not an option. Otherwise, you can use an array, it can be simpler (less risk of forgetting about free memory, for example)

Example:

  • to maintain a three-dimensional position, you can use an array since it has 3 coordinates.
  • to create a sieve for calculating prime numbers, you can use the parameter to get the maximum value and thus use dynamic allocation to create a memory area
+1
source

An array is used to allocate memory statically and at a time. Memory allocation dynamically requires malloc.

eg. int numbers[10];

This will allocate memory statically, and it will be continuous memory.

If you don’t know the number of numbers, use a variable of type count.

 int count; int *numbers; scanf("%d", count); numbers = malloc ( sizeof(int) * count ); 

This is not possible with arrays.

+1
source

Dynamic does not apply to access. The dynamic size of malloc. If you just use a constant number, for example. for example, 10 in your example, this is nothing better than an array. The advantage is that you do not know in advance how important this is, for example. because the user can enter the size at runtime. Then you can highlight the variable, for example. like malloc(sizeof(int) * userEnteredNumber) . This is not possible for an array, since you should know that at compile time (maximum) size.

0
source

All Articles