tl;dr – Could you please expand on the 4 comments in the first code snippet below? Specifically what is meant be deref
I’m a long time Java developer looking to learn C++. I came across this website aimed at developers in my situation.
int x, *p, *q;
p = new int;
cin >> x;
if (x > 0) q = &x;
*q = 3; // 1. deref of possibly uninitialized ptr q
q = p;
p = new int; // 2. potential storage leak (if x != 0 this
// memory will not be returned to free storage)
*p = 5;
delete q;
*q = 1; // 3. deref of deleted ptr q
q = p;
if (x == 0) delete q;
(*p)++; // 4. deref of possibly dangling ptr p (if x is zero)
Although I thought I understood how pointers work, I am finding the comments difficult to understand.
My take;
- We are either assigning x (& *q of course) to be 3 OR if q != &x then q has a just value as it was uninitialized and we have just assigned a random piece of memory to the value 3. I’m not sure how you can dereference something that isn’t initialized?
- This is fine
- What’s wrong with dereferencing a deleted pointer? After ‘delete q’ is *q meaningless?
- What’s wrong with dangling pointers? Is the memory viable for reallocation now that we have deleted it even though we still have a pointer to it?
I think my basic misunderstanding is about just declaring an int pointer, does this allocate memory too? Is it on the stack or the heap?
Also does dereference just mean ‘read the value at the address of the pointer’? I think my confusion is that I interpret it as loosing a reference to some data as in;
int *x;
x = new int;
*x = 5;
x = new int; // Dereferencing the first bit of memory allocated.
Thanks for you patience I hope that this makes some sense as a question,
Gav
Simply put: A pointer is an address of a variable whose values you may be interested in.
Dereferencing is the act of accessing that value — by prepending the
*(dereferencing operator) to the pointer variable. The access may be for reading, writing or both.If you do not initialize a pointer to a valid address (or the special value NULL) — you do not know what that variable contains. Dereferencing will try to take whatever is there and treat it as an address. This is undefined behavior — all bets are off, anything might happen, though if you are lucky you’ll end up with a trap/hardware exception.
Exactly. Because,
pwas holding the address of some memory you allocated. Not freeing up system resources causes a leak. Dereferencing a deleted pointer is the same as dereferencing an uninitialized pointer — you don’t know what value it may contain.Again, UB.
True. You have UB for
x == 0. Dangling pointers are dangerous because they creep up at the most inopportune time, format your hard disk and are never seen again. It becomes impossible to reasonably justify how your program will behave.