Dynamically allocated memory must be freed manually
When using dynamic arrays in languages like C or C++, you typically allocate memory using functions like malloc
or new
, respectively. If this allocated memory is not explicitly freed, it remains allocated until the program terminates. This can potentially cause a memory leak, especially in long-running programs where memory usage accumulates over time.
In C, use free()
:
int *arr = (int *)malloc(sizeof(int) * 10);
free(arr); // explicitly freed the memory
In C++, use delete[]
:
int *arr = new int[10];
delete[] arr; // explicitly freed the memory
In many other programming languages, memory management is handled automatically by a garbage collector. In such cases, you do not need to manually free memory, as the garbage collector reclaims unused memory for you (250131121405).