What is the purpose of `malloc()` in C?

What is the purpose of malloc() in C?

a) To dynamically allocate memory
b) To deallocate memory
c) To allocate memory on the stack
d) To initialize variables

Answer:

a) To dynamically allocate memory

Explanation:

The malloc() function in C is used to dynamically allocate memory at runtime. It allocates a specified number of bytes in the heap and returns a pointer to the allocated memory. If the allocation fails, malloc() returns NULL. Since the memory is allocated dynamically, it must be freed using free() to avoid memory leaks. malloc() is often used when the size of the data structure is not known at compile time, or when memory needs to be allocated based on user input or other runtime conditions.

Understanding malloc() is critical for managing dynamic memory in C, especially in programs that handle large or variable-sized data structures.

Reference links:

https://www.rameshfadatare.com/learn-c-programming/

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top