Code 1: Variable Length Array (VLA)
int n;
scanf("%d", &n);
int arr[n];
Features:
- Array Allocation:
- The array is declared on the stack.
- Stack memory is limited in size, so VLAs are unsuitable for very large arrays.
- Automatic Deallocation:
- The array is automatically deallocated when it goes out of scope (at the end of the function).
- You don’t need to free the memory manually.
- Portability:
- VLAs are part of the C99 standard and optional in C11. Some compilers (e.g., MSVC) do not support VLAs.
Pros:
- Simpler syntax; no need to manage memory explicitly.
- Automatically deallocated, reducing the risk of memory leaks.
Cons:
- Limited to stack memory, which is typically small (e.g., a few MB).
- Not available in all compilers or environments.
Code 2: Dynamically Allocated Array (Heap Allocation)
arr = (int*) malloc(num * sizeof(int));
Features:
- Array Allocation:
- The array is allocated on the heap.
- Heap memory is much larger than the stack, so you can handle very large arrays.
- Manual Deallocation:
- You must explicitly free the memory using
free(arr)
when it’s no longer needed.
- You must explicitly free the memory using
- Portability:
- Works across all C standards and compilers.
Pros:
- Suitable for large arrays due to the larger size of heap memory.
- Portable and supported in all C compilers.
Cons:
- Requires explicit memory management (
malloc
andfree
). - Forgetting to free the memory leads to memory leaks.
Which to Use?
Use VLAs (Code 1):
- If the array size is small and the compiler supports VLAs.
- When you want simplicity and don’t need to worry about manual memory management.
Use Heap Allocation (Code 2):
- If the array size can be large and may exceed stack limits.
- When you need portability across different compilers or standards.
- If the array needs to persist beyond the function’s scope.
Example Decision:
- Small arrays and local use: Use Code 1.
- Large arrays or arrays needed globally/for longer durations: Use Code 2.
Best Practice for Dynamic Memory:
If you use Code 2, always pair malloc
with free
to prevent memory leaks:
free(arr);