NULL pointer dereference

A NULL pointer dereference occurs when a program attempts to read or write memory using a NULL pointer. This error causes a segmentation fault.

Consequences

Running a program that contains a NULL pointer dereference generates an immediate segmentation fault error.

Detecting the error

The Memory Analysis tool detects the passing of a NULL pointer to string and memory functions if Verify parameters in string and memory functions is checked under Memory Errors in the configuration.

Information returned by the Memory Problems view

The notification for this type of memory error includes the following details:
  • Severity: ERROR
  • Description: null pointer dereference
  • Pointer: 0x0
  • Trap Function: one of: strcat strdup strncat strcmp strncmp strcpy strncpy strlen strchr strrchr index rindex strpbrk strspn (first argument only) strcspn strstr strtok
  • Alloc Kind: always blank
  • Location: source file and line of code where the error occurred (e.g., main.c:59)
  • Count: always 1
Note:

The Memory Analysis tool doesn't trap this error with the following functions: memccpy memchrv memmove memcpy memcmp memset bcopy bzero memccpy memchrv memmove memcpy memcmp memset bcopy bzero bcmp bcmp

How to address a NULL pointer dereference

In the code, you can explictly check for NULL returned by functions that can return NULL and then stored into pointer variables, and for all pointer values passed to the function where the problem occurred.

Example

The following code shows an example of a NULL pointer dereference (which occurs if the program is called with no arguments):
int main(int argc, char ** argv) {
  char buf[255];
  char * ptr = NULL;
  if (argc > 1) {
    ptr = argv[1];
  }
  ...
  strcpy(buf,ptr);
  return 0;
}