How does the malloc()
function work in C?
a) Allocates a block of memory of a specified size
b) Frees allocated memory
c) Allocates memory for a single variable
d) Allocates memory for an array
Answer:
a) Allocates a block of memory of a specified size
Explanation:
The malloc()
function in C stands for memory allocation. It dynamically allocates a block of memory on the heap of a specified size (in bytes) and returns a pointer to the beginning of the block. If the allocation fails, malloc()
returns a NULL
pointer. Unlike arrays, which are allocated on the stack, memory allocated by malloc()
persists until explicitly freed using the free()
function.
Malloc()
is often used when the size of the data to be stored cannot be determined before the program runs, allowing for more flexible memory management.