NULL pointer dereference

A NULL pointer dereference is a sub type of an error causing a segmentation fault. It occurs when a program attempts to read or write to memory with a NULL pointer.

Consequences

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

Note: For instructions about enabling error detection in the IDE, see Enable memory leak detection.

When the memory analysis feature detects this type of error, it traps these errors for any of the following functions (if error detection is enabled) when they are called within your program:

strcat strdup strncat strcmp strncmp strcpy strncpy strlen strchr strrchr index rindex strpbrk strspn (only the first argument) strcspn strstr strtok

The memory analysis feature doesn't trap errors for the following functions when they are called:

memccpy memchrv memmove memcpy memcmp memset bcopy bzero memccpy memchrv memmove memcpy memcmp memset bcopy bzero bcmp bcmp

Enabling error detection for a NULL pointer dereference

To enable error detection for the NULL pointer dereference:

  1. In the Launch Configuration window, select the Tools tab.
  2. Expand Memory Errors and select the Enable error detection checkbox.
  3. To detect the passing of a zero (0) pointer to string and memory functions, select Verify parameters in string and memory functions.
  4. To detect the freeing of a zero (0) pointer, select Enable check on realloc()/free() argument.

Message returned to the QNX IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:

For a list of error messages returned by the Memory Analysis tool, see Summary of error messages for Memory Analysis.

How to address a NULL pointer dereference

You can perform an explicit check for NULL for all pointers returned by functions that can return NULL, and when parameters are passed to the function.

Example

The following code shows an example of a NULL pointer dereference:

int main(int argc, char ** argv){
  char buf[255];
  char * ptr = NULL;
  if (argc>1) {
    ptr = argv[1];
  }
  strcpy(str,ptr);
  return 0;
}