In C, memory for variables can be allocated either on the stack or in the heap.
malloc, calloc, realloc, and is freed manually via free. The amount of memory is limited by system capabilities, but access is slower and manual control of freeing is required.When to use stack:
When to use heap:
// On the stack int arr[10]; // On the heap int* parr = malloc(sizeof(int) * 10); // Don't forget to free the memory free(parr);
Question: What happens if you do not call free on an array allocated via malloc?
Answer: A memory leak occurs. Dynamically allocated memory will not be automatically freed, and over time this can lead to the application's memory or the entire system running out of memory.
void leak() { int* leakArr = malloc(100 * sizeof(int)); // No call to free(leakArr), memory is lost }
Story
In one project, programmers allocated memory for a structure describing a user's session via malloc but forgot to call free at the end of their work with the session. As a result, the project lost memory for several days, and the server crashed with an out-of-memory error. The issue was only resolved after profiling with Valgrind and fixing all missed frees.
Story
One developer allocated a large array (up to 10 MB) on the stack for temporary calculations. On a server with a small stack size, this led to application crashes with stack overflow errors. After analysis, they had to move the buffer to the heap.
Story
One of the developers decided to store long strings on the stack, but the size of the string was subjectively determined by the user. When entering a very long string, the application crashed with an access violation error. Ultimately, it was decided to move the input data to the heap with length checking.