Reputation: 26647
The malloc example I'm studying is
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *vec;
int i, size;
printf("Give size of vector: ");
scanf("%d",&size);
vec = (int *) malloc(size * sizeof(int));
for(i=0; i<size; i++) vec[i] = i;
for(i=0; i<size; i++)
printf("vec[%d]: %d\n", i, vec[i]);
free(vec);
}
But I can make a program behave at runtime like this program behaves writing it in C wihout malloc, can't I? So what's the use of malloc here?
Upvotes: 0
Views: 256
Reputation: 158469
This specific example could have been done using variable length arrays which were supported by the standard since c99
, now optional as of the 2011 standard. Although if size
is very large allocating it on the stack would not work since the stack is much smaller than available heap memory which is what malloc
will use. This previous post of mine also has some links on variable length arrays you might find useful.
Outside of this example when you have dynamic data structures using malloc
is pretty hard to avoid.
Upvotes: 2
Reputation: 67193
Two issues:
First, you might not know how much memory you need until run time. Using malloc()
allows you to allocate exactly the right amount: no more, no less. And your application can "degrade" gracefully if there is not enough memory.
Second, malloc()
allocated memory from the heap. This can sometimes be an advantage. Local variables that are allocated on the stack have a very limited amount of total memory. Static variables mean that your app will use all the memory all the time, which could even potentially prevent your app from loading if there isn't enough memory.
Upvotes: 1
Reputation: 12907
It is dynamic memory allocation.
The very important point there is that you don't know how much memory you'll need because the amount of memory you must end up with is dependant on the user input.
Thus the use of malloc, which takes size
as part of its argument, and size
is unknown at compile-time.
Upvotes: 4