How is memory deallocated in C?
a) Using the
free()
functionb) Using the
malloc()
functionc) Automatically when a variable goes out of scope
d) Using the
return
statementAnswer:
a) Using the
free()
functionExplanation:
In C, memory that has been dynamically allocated using malloc()
, calloc()
, or realloc()
must be explicitly deallocated using the free()
function. Failing to deallocate memory can lead to memory leaks, where the memory remains allocated even though it is no longer needed, eventually causing the program to consume all available memory. The free()
function takes a pointer to the allocated memory as its argument and releases the memory back to the system for reuse.
Understanding how to properly deallocate memory using free()
is crucial for writing efficient and memory-safe C programs.