-1

I just learned that Dynamic Memory Allocation can be done using the malloc() function. But I just discovered that in C I can do the following which just works fine for me:

int n,i,avg=0;
printf("Enter the Number of elements you want to enter:");
scanf("%d",&n);
int a[n];
printf("Enter %d elements:",n);
for(i=0;i<n;i++){scanf("%d",&a[i]); avg+=a[i];}

Plzz, tell me what's the difference in using malloc() and the above code I used.

1 Answers1

1

Dynamic memory allocation is done in heap memory. The one you showed is done dynamically but in stack.

Trying to keep it less complex, let's try to understand this.

You may have studied stack data structure in your classes. That's what is used for allocation in case of this:

int a[n];

Stack size obviously has a limit. Like if 100 was the maxsize, allocating beyond it would cause a stack overflow.

The issue is that there is no way to handle such a stack overflow at runtime.

Let's say n was 10000 and suppose there was't enough memory. It would just cause a trap.

If you want, you can see it live by allocating memory for a large number, like 100000000ULL. It will just crash.

To allocate in stack, you can also use alloca(3). If you read it's description, it says:

If the allocation causes stack overflow, program behavior is undefined.

So basically no way to have an ensured check. Generally if it fails program terminates unless you have a unique OS that gives you the capability to handle it.

Variable length arrays(int a[n]) and alloca(3) allocate in stack.

malloc(2) allocates in heap.

On return, as per the man page,

On error, these functions return NULL.

So you can make a runtime check:

int *a = malloc(1234);
if (a == NULL) {
    fprintf(stderr, "malloc(2) failed!\n");
    // handle it
}
Mihir Luthra
  • 6,059
  • 3
  • 14
  • 39