Hi,
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