In this section:

Overview

This error is generated whenever a function returns a pointer to a (non-static) local variable. Since the stack frame of this routine will disappear when the function returns, this pointer is never valid.

Additional configuration required

In order for Insure++ to find this error, the suppressEDGWarning off option is required.

CodeDescriptionEnabledReportedPlatform
RETURN_DANGLINGReturning pointer to local variable(tick)CompilationWindows/Unix


Problem

The following code shows the routine foo returning a pointer to a local variable.

/*
 * File: retdngl.c
 */
char *foo()
{
	char b[10];
	return b;
}

main()
{
	char *a = foo();
	return 0;
}

Diagnosis During Compilation

[retdngl.c:7] **RETURN_DANGLING**
	Returning pointer to local variable: b.
>>		 return b;
  • Line 1: Source line at which the problem was detected.
  • Line 2: Description of the problem and the expression that is in error.

Repair

The pointer returned in this manner can be made legal in one of several ways:

  • Passing the required buffer from the calling function and, if required, also passing the size of the buffer as another parameter.
  • Declaring the memory block static in the called routine, i.e., line 6 would become:
    static char b[10];
  • Allocating a block dynamically instead of on the stack and returning a pointer to it, e.g.:

    char *foo()
    {
    	return malloc(10);
    }
  • Making the memory block into a global variable rather than a local one.

Occasionally, the value returned from the function is never used in which case it is safest to change the declaration of the routine to indicate that no value is returned.

  • No labels