C ErrorsLesson 46Free preview
C NULL
This lesson is part of C · All levels
Summary
NULL is a special value that marks that a pointer does not point to any object, and the mere-dereference pointer NULL usually crashes the program. So before using a malloc result pointer or a function that can fail, always check if it is. After calling free on a pointer, it is best to set the pointer to NULL immediately to avoid double free and use-after-free.
Key points
- NULL is defined by standard header such as stddef.h as an invalid pointer marker.
- Dereference includes the most frequently occurring segmentation fault behavior.
- Pointer retrieval functions often send NULL when they fail, for example malloc and fopen.
- After free, set the pointer to NULL to prevent access to memory that has already been deleted.
- The p == NULL comparison is easier to read than the !p for the code that is clearly meant.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.