ProgrammingC Developer

Describe the mechanism of dynamic memory allocation and deallocation in C, the main functions (malloc, calloc, realloc, free), and common mistakes in their usage.

Pass interviews with Hintsage AI assistant

Answer

In C, dynamic memory management is handled through functions from the stdlib.h library:

  • malloc(size_t size) — allocates a block of memory of the specified size. The memory is not initialized.
  • calloc(size_t nmemb, size_t size) — allocates a block of memory for an array of nmemb elements of the specified size and initializes it to zero.
  • realloc(void *ptr, size_t size) — changes the size of a previously allocated block of memory.
  • free(void *ptr) — frees a previously allocated block.

Example usage:

int *arr = (int *)malloc(10 * sizeof(int)); if (arr == NULL) { // Handle memory allocation error } // ... working with arr ... free(arr);

It is important to always check the result of memory allocation for NULL and not forget to call free to avoid memory leaks.

Trick question

What will be the result of the following code?

int *arr = malloc(sizeof(int) * 5); free(arr); free(arr);

Answer: Calling free on the same memory area multiple times leads to undefined behavior. A pointer should only be freed once.

Examples of real errors due to ignorance of the subtleties of the topic


Story

In an automated testing project, there were regular crashes. The culprit was a system loop where after each pass, memory allocated through malloc was forgotten to be freed. As a result of prolonged tests, the system "consumed" all available memory and froze.


Story

The implementation of a dynamic array used realloc without checking the return result. On failure (realloc returned NULL), the pointer to the old memory was lost, leading to a memory leak. Subsequent attempts to work with the memory resulted in a segmentation fault.


Story

A developer was tasked with integrating an outdated C module, where memory was freed using free twice in a row for the same pointer. On most operating systems, errors did not appear, but on a new platform, the application started crashing, with the cause discovered long after: double-free.