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.
Loading...
Related Quiz
- In C, a function pointer can be used to call a function without knowing its ________ at compile time.
- You're developing a program that needs to frequently update specific records in a large binary file. Which file handling functions would be most useful to efficiently locate and update records?
- The ______ function in C can be used to change the position of the file pointer in a stream.
- How does the 'extern' keyword affect the scope and lifetime of a variable in C?
- In the context of function pointers in C, a callback function is a function that is passed as a(n) ________ to another function.