How can you handle an error when attempting to allocate memory using malloc() in a C program?

  • Check if the return value of malloc() is NULL and handle accordingly.
  • Use try-catch blocks to handle memory allocation errors.
  • Set a flag in case of an error and handle it in a separate error-handling function.
  • Call exit() to terminate the program if malloc() fails.
The correct option is "Check if the return value of malloc() is NULL and handle accordingly." Malloc() returns a NULL pointer if it fails to allocate memory. It's crucial to check this return value to handle memory allocation errors gracefully.
Add your answer
Loading...

Leave a comment

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