0

I was learning about malloc, calloc, free and realloc in C but I don't get when should I use these functions.

For example: if I want to create a program in C that creates an array and the size of it is determined from user input:

   int n;
   printf("Enter THe Number of element in Array:..\n");
   scanf("%d",&n);
   int x[n];
   for(int i = 0 ; i < n ; i++)
   {

       x[i] = i+ 1;
   }
      for(int y = 0 ; y < n ; y++)
   {

       printf("%d\n",x[y]);
   }

output:

Enter THe Number of element in Array:..
5
1
2
3
4
5

So here I created this program without using Dynamic memory allocation, which makes things more complicated to me.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Test065
  • 49
  • 6

4 Answers4

1

Heap is usually much larger than the area used to accommodate automatic variables and the static storage area (global variables).

So you may use the dynamic allocation when:

  1. you need to allocate the memory, and free it after use
  2. when you need to change the size of the memory allocated.
  3. when you need memory which will be allocated in one task/function and then passed to another task/function and used after the scope has terminated
  4. you need to allocate a large chunk of memory.

but in your example

int x[n];

is not the dynamic allocation. You simply allocate the automatic array with the size set runtime. You cant change the size of it, you cant also use it when you exit the scope as its lifetime is bound to the scope it was defined in.

0___________
  • 60,014
  • 4
  • 34
  • 74
1

Your example uses something called a variable-length array, which can substitute for dynamic memory in some circumstances. However, VLAs are not supported in all versions of C (they were first introduced in the 1999 revision and made optional in the 2011 revision) and they cannot be members of struct or union types, nor may they be used as “globals” at file scope. Like fixed-size arrays, their storage is released as soon as you exit their enclosing scope (i.e., block or function). They usually cannot be arbitrarily large.

You would use dynamic memory (malloc, calloc, or realloc) under the following circumstances:

  • You need to allocate a large block of memory;
  • You need to be able to grow or shrink that memory;
  • You need that memory to persist beyond the lifetime of the function that allocated it;
John Bode
  • 119,563
  • 19
  • 122
  • 198
0

One (very common, in fact) case is that using memory allocated locally (usually, but not necessarily, on the stack), as your example does, will not work if that memory is allocated inside a function that is called from elsewhere, because that memory will be reset - or 'lost' - when that function returns.

In such a case, you need to dynamically allocate memory (on the heap), using a malloc (or related) call. Memory thus allocated will be 'global', and can be accessed by any other part of the program (so long as it has the pointer), until it is explicitly freed via a call to the free() function.

Here's an example:

#include <stdio.h>
#include <stdlib.h>

int* newArray(int n)
{
//  int x[n]; // Won't work: This is local (stack) memory that is lost on return
    int* x = malloc(n * sizeof(int)); // Works: This is global (heap) memory
    return x;
}

int main()
{
    int n;
    printf("Enter The Number of Elements in Array: ");
    scanf("%d", &n);
    int* x = newArray(n);
    for (int i = 0; i < n; i++) {
        x[i] = i + 1;
    }
    for (int y = 0; y < n; y++) {
        printf("%d\n", x[y]);
    }
    free(x); // You MUST free memory that you've allocated with malloc
    return 0;
}

(You can try uncommenting the "won't work" line and commenting out the "works" line, to see for yourself.)

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • is not "invalidated". It ends its life. – 0___________ Jun 07 '20 at 09:58
  • 1
    Where the auto variables are placed is up to implementation. It does not have to be stack. And it actually does not matter at all. – 0___________ Jun 07 '20 at 10:03
  • it does not have to be function https://godbolt.org/z/_6MBBS I did not exit the function to have an UB – 0___________ Jun 07 '20 at 10:14
  • @P__J__ No, it doesn't *have* to be in a function, but the example I gave is about when it ***is*** in a function. Just **one** example. Your linked code is a *different* example. – Adrian Mole Jun 07 '20 at 10:15
  • the memory is not **lost** or "reset" - only the object ends it life. – 0___________ Jun 07 '20 at 10:24
  • 1
    @P__J__ Can you name an implementation which does not put automatic variables on the stack (*some kind* of stack), or was that a purely irrelevant remark? I believe that since Algol60, that is, for more than 60 years, automatic variables have been on the stack if they were in memory at all (which they must be here because their address is being taken). – Peter - Reinstate Monica Jun 07 '20 at 14:31
0

you can use dynamic memory allocation to allocate variables in the run time and there are some steps you should follow them where you need to allocate the memory by using this

 int* x = malloc(n * sizeof(int)); 

and free it after use by using this

free(x); 
Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
sara hamdy
  • 402
  • 2
  • 12