Select Page

Dangling pointers in C

by 08.04.2023Dynamic Memory Management in C

The pointer is dangling when it still references to the memory that has been freed. In this case the pointer doesn’t point to a valid object. It can cause various problems:

  • Unpredictable behavior when the memory is accessed,
  • Segmentation faults when the memory is not accessible,
  • Security risks.

This can happen when the memory is accessed after it was freed or when the pointer is returned to an automatic variable in a previous function call.

Examples of dangling pointers

#include <stdlib.h>
#include <stdio.h>

int	main(void)
{
	int	*ptr;

	ptr = (int *) malloc(sizeof(int));
	*ptr = 10;
	printf("%d, %p", *ptr, ptr);
	free(ptr);
	return (0);
}

The memory that was freed by free function should not be used. Most systems will not prevent its further access or modification.

	free(ptr);
	*ptr = 5; //Dangling pointer

The result of operation above would be unpredictable.

Dealing with Dangling pointer

Debugging the errors occured by dangling pointers can be complicated. There are several approaches to resolve this issue:

  • Set the pointer to NULL after freeing it. If the multiple copies of pointer still exist (aliased pointers), the problem would still resist.
  • Write special function to replace the free function.
  • Some systems ovewrite data (0xCC, 0xDD, 0xDEADBEEF, …) when the memory is freed so the coder can know that the program is accessing the freed memory. (Displaying pointer value can be useful)
  • Use third-party tools to dect dangling pointers.

It can be usefull to display pointer values.

Garbage Collection in C

The deallocated memory is called garbage. Garbage collection describes its processing.

SOURCES:
[1] Understanding and Using C Pointers by Richard Reese (O’Reilly). Copyright 2013 Richard Reese, Ph.D. 978-1-449-34418-4