Search

ParaSoft

HOME
PRODUCTS
SUPPORT
ABOUT
WHAT'S NEW
EVENTS


Insure++

Quick facts

Add-on Modules:
   -INUSE
   -TCA

Comparisons

Technical Papers

Support & Manuals

FAQs

Recent Reviews

User Testimonials

Press Releases


Insure tool to debug c++





Insure++ Reference - RETURN_DANGLING



RETURN_DANGLING

Returning pointer to local variable

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.

Problem

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

	1:	/*
	2:	 * File: retdngl.c
	3:	 */
	4:	char *foo()
	5:	{
	6:		char b[10];
	7:		return b; bug
	8:	}
	9:
	10:	main()
	11:	{
	12:		char *a = foo();
	13:		return (0);
	14:	}

Diagnosis (during compilation)

1.	[retdngl.c:7] **RETURN_DANGLING**
2.		Returning pointer to local variable: b.
	>> 		return b;
  1. Source line at which the problem was detected.
  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.

  • 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.


< READ_WILD > RETURN FAILURE
Tools to debug c++ and java
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft