In this section:
This error is generated whenever an expression operates on the NULL
pointer.
|
In the following code, the pointer a
is initialized to zero because it is a global variable. The pointer is manipulated, generating the EXPR_NULL
error.
* * File: expnull.c */ char *a; main() { char *b; b = &a[1]; return (0); } |
[expnull.c:10] **EXPR_NULL** >> b = &a[1]; Expression uses null pointer: a[1] Stack trace where the error occurred: main() expnull.c, 10 |
One potential cause of this error is shown in the example. The a
pointer is a global variable and will be initialized to zero by the compiler. Because this variable is never modified to point to anything else, it is still NULL
when first used. In the following example, an assignment is added as one way to correct the code:
/* * File: expnull.c (modified) */ char *a; main() { char *b, c[10]; a = c; b = &a[1]; return (0); } |
It can also be corrected by allocating a block of memory.
A second possibility is that the pointer was set to zero by the program at some point before its subsequent use and not re-initialized. This is common in programs which make heavy use of dynamically allocated memory and which mark freed blocks by resetting their pointers to NULL
.
A final common problem is caused when one of the dynamic memory allocation routines, malloc
, calloc
, or realloc
, fails and returns a NULL
pointer. This can happen either because your program passes bad arguments or simply because it asks for too much memory. A simple way of finding this problem with Insure++ is to enable the RETURN_FAILURE error code and run the program again. It will then issue diagnostic messages every time a system call fails, including the memory allocation routines.