Dangling Pointers

What Are Dangling Pointers?

Issues with Dangling Pointers

Example of a Dangling Pointer

int *initArray(int howLarge) {
  int myArray[howLarge];
  for (int i = 0; i < howLarge; i++) {
    myArray[i] = i;
  }
  int *p = myArray;
  return p;  // Returns pointer to deallocated memory
}

Risks and Misconceptions

Memory Behavior

Key Takeaway: ALWAYS avoid returning pointers to local variables from functions to prevent creating dangling pointers and undefined behavior in your code.


Array Size

Array Indices and Size