In C, arrays are the basic structure for storing an ordered set of elements of the same type. They provide quick access by index and are closely related to pointer operations. Arrays can be declared statically, automatically (on the stack), or dynamically (in the heap). The type of allocation affects the lifespan of the array, its availability from different parts of the code, and the memory management requirements.
Background
Initial C allowed only static and automatic arrays, but with the advent of dynamic memory allocation (functions malloc, calloc, free), new design patterns emerged that increased code flexibility.
Problem
Developers often make mistakes with sizes, lifetimes, and cleanup of arrays, leading to leaks, race conditions, and memory corruption.
Solution
Careful choice of storage type based on the task, diligent tracking of initialization, and timely release of memory for dynamic arrays.
Code example:
#include <stdio.h> #include <stdlib.h> int main() { // Automatic (on the stack) int auto_arr[5] = {1,2,3,4,5}; // Static (lives as long as the program runs) static int static_arr[5]; // Dynamic (in the heap) int *dyn_arr = malloc(5 * sizeof(int)); for (int i = 0; i < 5; i++) dyn_arr[i] = i * 2; // Usage for (int i = 0; i < 5; i++) printf("%d ", dyn_arr[i]); printf(" "); free(dyn_arr); return 0; }
Key features:
Can you find out the size of a dynamic array using sizeof?
No, sizeof(ptr) for a dynamic array will return the size of the pointer, not the array. You need to manually keep track of the size or use a separate variable.
int* arr = malloc(10 * sizeof(int)); printf("%zu ", sizeof(arr)); // Size of the pointer, not the array
What happens when you go out of bounds of an array?
In C, there is no automatic boundary checking for arrays: accessing out of bounds leads to undefined behavior. Errors are detected only at runtime or may go undetected entirely.
Can you return a local (automatic) array from a function?
No! An array declared inside a function is removed after it finishes. Returning such an array leads to accessing already freed memory.
int* create_wrong_array() { int arr[10]; return arr; // Error: returning a pointer to stack }
A developer creates an array on the stack and returns a pointer to it from a function. The program sometimes crashes or returns garbage.
Pros:
Cons:
Using dynamic allocation with size passing together with the pointer, memory cleanup via free. All memory releases are checked by unit tests.
Pros:
Cons: