From the course: Secure Coding in C

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Checking for NULL pointers

Checking for NULL pointers - C Tutorial

From the course: Secure Coding in C

Start my 1-month free trial

Checking for NULL pointers

- [Instructor] The defined constant, null, references as an undefined memory location. It's useful as a test for any function that returns a pointer to ensure that the function was successful. In this code the malloc function allocates 27 characters of storage, referenced by pointer, alphabet. The pointer is filled in the for loop at line 11, and then output at line 16. Build, and according to the build messages, there were no errors or warnings, let's run. And it looks like the code ran just fine. This code shows one vital test missing from the preceding example. The test is at line 10, and it determines whether the malloc function returned a null pointer, indicating failure to allocate memory. Yes, even on a quantity this small perform this type of test with any memory allocation function, or function that returns a pointer. This code outputs a file at line eight, closes the file at line nine, that's it. Building…

Contents