0

Is this a dangling pointer?

int x = 25;
int** arr = new int*[5];
*arr[1] = x;

I can't figure out why this doesn't work... *arr[1] is just a pointer, and is pointing to a valid memory address.

4
  • 1
    Where does arr[1] get assigned (i.e. it's currently uninitialized with your code)? Feb 18, 2013 at 21:39
  • @H2CO3: It's just a small amount of UB. As far as UB/post goes, this is one of the milder cases!
    – Kerrek SB
    Feb 18, 2013 at 21:41
  • @KerrekSB My favorite today was the violation of the restrict keyword - OP was sprintffing a buffer onto itself. What a shame (and I even didn't get any upvotes for pointing that out).
    – user529758
    Feb 18, 2013 at 21:42
  • BTW, a dangling pointer is a pointer to memory that has been freed, but has not been set back to NULL. Therefore, if you accidently access that pointer thinking that it's still "good", "bad" things will happen. Feb 18, 2013 at 21:45

1 Answer 1

5

arr[1] is an int*, and it's uninitialized. It's undefined behaviour to dereference it.

You could say arr[1] = &x;, then arr[1] would point to x and *arr[1] would be 25.


Don't forget delete [] arr; when you're done.

1
  • Twas a syntax issue then...For some reason, I was thinking that line was dereferencing the int** itself and not the one in the specified location. Thanks Kerreck! Feb 18, 2013 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.