What does malloc() return when the requested memory allocation cannot be satisfied?

Options

  • A. A valid pointer to the requested memory
  • B. NULL or a null pointer value
  • C. The value zero as an integer object
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. NULL or a null pointer value

Detailed Explanation

Answer: (B) NULL or a null pointer value

If malloc() cannot allocate the requested memory, it returns a null pointer value.

A program should check the returned pointer before attempting to use the allocated memory.

For example:

int* p = (int*)malloc(100 * sizeof(int));

if (p == NULL) { /* allocation failed */ }

This check helps prevent the program from using an invalid allocation result.