What are the dangling pointers in this C code at location 2?

0
2
Asked By CuriousCoder92 On

I'm working through some C code involving dynamic memory allocation and I'm a bit confused about dangling pointers. In the code, I have multiple pointers: `a`, `t`, `e`, and `x`. After I call `free(x)` at location 1, which pointers become dangling at location 2? I think that only `e` and `t` should be dangling, but my friend argues that `a` will also be dangling. Can someone clarify this?

1 Answer

Answered By MemoryWhiz88 On

At location 2, `e` is definitely a dangling pointer because it was set to point to the memory location of `x` before `x` was freed. Since the lifetime of that memory ended with `free`, any pointer referencing it becomes dangling.
Also, `y` and `a` are also dangling pointers because they point to the same memory location as `x` did. When `x` goes out of scope after the block, `y` and `a` lose their valid memory reference too. It’s a bit tricky, but `x` itself isn’t a dangling pointer because it's out of scope; it's more accurate to say the last value it held is now dangling.

CodeSleuth54 -

I see what you mean! Just to clarify, if `a` held the address of a memory location that was freed, isn’t that considered a memory leak? Because `a` would still be pointing to that freed memory.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.