In this section:

Overview

This error is generated whenever a parameter declared as an array is actually passed a pointer to a block of memory that has been freed.

CodeDescriptionEnabledReportedPlatform
PARM_DANGLING

Array parameter is a dangling pointer

(tick)RuntimeWindows/Unix


Problem

The following code frees its memory block before passing it to foo.

/*
 * File: parmdngl.c
 */
#include <stdlib.h>

char foo(a)
	char a[10];
{
	return a[0];
}

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

Diagnosis at Runtime

[parmdngl.c:7] **PARM_DANGLING**
>>		 {
Array parameter is dangling pointer: a
Pointer		 : 0x0001adb0
In block	 : 0x0001adb0 thru 0x0001adb9 (10 bytes)
			block allocated at:
				malloc() (interface)
				main() parmdngl.c, 15
		stack trace where memory was freed:
				main() parmdngl.c, 16
Stack trace where the error occurred:
				foo() parmdngl.c, 7
				main() freedngl.c,17
  • 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 4: Value of the pointer that was passed and has been deallocated.
  • Line 5: Information about the block of memory addressed by this pointer, including information about where this block was allocated.
  • Line 10: Indication of the line at which this block was freed.
  • Line 13: Stack trace showing the function call sequence leading to the error.

Repair

This error is normally caused by freeing a piece of memory too soon. A good strategy is to examine the line of code indicated by the diagnostic message which shows where the memory block was freed and check that it should indeed have been de-allocated.

A second check is to verify that the correct parameter was passed to the subroutine.

A third strategy which is sometimes useful is to NULL pointers that have been freed and then check in the called subroutine for this case. Code similar to the following is often useful:

#include <stdlib.h>
char foo(a)
	char *a;
{
	if(a) return a[0];
	return '!';
}
main()
{
	char *a;
	a = (char *)malloc(10);
	free(a);
	a = NULL;
	foo(a);
	return (0);
}

The combination of resetting the pointer to NULL after freeing it and the check in the called subroutine prevents misuse of dangling pointers.

  • No labels