In this section:
Overview
This error is generated whenever a parameter declared as an array is actually passed a NULL
pointer.
Code | Description | Enabled | Reported | Platform |
---|---|---|---|---|
PARM_NULL | Array parameter is | Runtime | Windows/Unix |
Problem
The following code fragment shows a function that is declared as having an array parameter. The function is actually invoked with a NULL
pointer. The value of array
is NULL
because it is a global variable, initialized to zero by default.
/* * File: parmnull.c */ int foo(a) int a[]; { return 12; } int *array; main() { foo(array); return (0); }
Diagnosis at Runtime
[parmnull:5] **PARM_NULL** >> { Array parameter is null: a Stack trace where the error occurred: foo() parmnull.c, 5 main() parmnull.c, 14
- Line 2: Source file and line at which the problem was detected.
- Line 3: Description of the problem and the name of the parameter that is in error.
- Line 5: Stack trace showing the function call sequence leading to the error.
Repair
A common cause of this error is the one given in this example, a global pointer which is initialized to zero by the compiler and then never reassigned. The correction for this case is to include code to initialize the pointer, possibly by allocating dynamic memory or by assigning it to some other array object. For example, we could change the main
routine of the example to the following
main() { int local[10]; array = local; foo(array); }
This problem can also occur when a pointer is set to NULL by the code (perhaps to indicate a freed block of memory) and then passed to a routine that expects an array as an argument. In this case, Insure++ distinguishes between functions whose arguments are declared as arrays and those with pointer arguments.
int foo(int a[]) // Declared as an array { int foo(int *a) // Declared as an argument {
Argument types will not generate an error if passed a NULL
argument, while array types will.
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 (see RETURN_FAILURE) and run the program again. It will then issue diagnostic messages every time a system call fails, including the memory allocation routines.
If your application cannot avoid passing a NULL
pointer to a routine, you should either change the declaration of its argument to the second style or suppress these error messages by suppressing PARM_NULL
.