I was curious with this:
What is the diference between:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
and:
char Buffer[MAX_BUF];
I was curious with this:
What is the diference between:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
and:
char Buffer[MAX_BUF];
Case 1: In
char Buffer[MAX_BUF];
Buffer
is an array of size MAX_BUF
. The allocation technique is called VLA.
Case 2: In
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
Buffer
is a pointer which is allocated a memory of size MAX_BUF
which is 1000
.
and, an array is not the same as a pointer, and C-FAQ has a Very Good collection detailing the reasons.
The major difference, in terms of usability and behaviour are:
malloc()
d memory should be free()
d. [Courtesy: Giorgi]Note: Wiki
For example, the GNU C Compiler allocates memory for VLAs on the stack.
I will add a bit info in terms of memory management, in addition to what others said.
1) The main difference is here:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
You need to manage the allocated memory manually, e.g., free Buffer
when you are done using it. Forgetting to free
it (or freeing it twice) may lead to trouble.
2) With the second case:
char Buffer[MAX_BUF];
You don't need to free anything. It will get destroyed automatically. Hence you avoid the task of handling the memory - which is good. You should try to evaluate always which approach you need.
Some points.
char* Buffer = malloc(MAX_BUF);
creates a char
pointer Buffer
, dynamically allocates MAX_BUF
bytes of memory via the malloc
and makes Buffer
point to the start of the allocated space. This memory is allocated on the heap.
char Buffer[MAX_BUF];
creates an array Buffer
of size MAX_BUF
which can hold a maximum of MAX_BUF
characters. Note that you are creating a Variable Length Array (a feature introduced in C99) since MAX_BUF
is a variable. This array may be created on the stack.
The most notable difference is scope. The VLA array will only be valid inside the scope where it is declared, while a dynamic array will be available everywhere in the program until you call free()
.
In practice, VLAs may be faster than dynamic memory, in case the compiler use stack allocation for the VLA. It is however not specified by the C standard where a VLA is allocated.
(A compiler could in theory allocate a VLA on the heap, but then the compiler would also be responsible for the clean-up. I don't think any such solutions exist. Every compiler I've used always declare VLAs on the stack.)
This means that VLAs are unsuitable to hold large amounts of data: you would risk stack overflow. This is not a concern when you are using dynamic memory however.
VLAs don't have the same portability as dynamic arrays, since awfully old compilers don't support VLAs. In theory, new C11 compilers don't have to suport VLAs either, though at this point I know of no compiler has been stupid enough to drop that support.
Comparison/summary: