ProgrammingC Developer

Explain the difference between stack and heap in C and when it is better to use each type of memory?

Pass interviews with Hintsage AI assistant

Answer.

In C, memory for variables can be allocated either on the stack or in the heap.

  • Stack — allocates memory automatically upon entering a function and frees it upon exiting. It is fast, but the amount of memory is limited by the size of the stack (usually a few MB).
  • Heap — allocates memory dynamically via 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:

  • For local variables, if their size is small and known at compile time.
  • For function arguments and small arrays.

When to use heap:

  • When the size of the memory is not known in advance.
  • For large or long-lived objects.

Code example:

// On the stack int arr[10]; // On the heap int* parr = malloc(sizeof(int) * 10); // Don't forget to free the memory free(parr);

Tricky question.

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.

Code example:

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.