From the course: Secure Coding in C
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Checking for NULL pointers - C Tutorial
From the course: Secure Coding in C
Checking for NULL pointers
- In this code, the malloc function allocates 27 characters of storage referenced by pointer alphabet. The buffer is filled in the for loop and then it's output. The terminating null character caps the string. Now, no warnings will appear on the build and the code appears to run fine. There's the alphabet, but hopefully you know what the problem is. Is the pointer returned by the malloc function null? Better do a check. (keyboard clacking) The null constant represents an undefined memory location when returned from the malloc function, null indicates a failure to allocate memory. Yes, even on a quantity this small. Perform this test with any memory allocation function or a function that returns a pointer. This code creates a file, and then it closes the file. No errors or warnings are generated and the file is successfully created. You can actually see it over here in the file list. output.txt. But a few tests are absent from this code. The fopen function returns a file handle fp…