#include <iostream>
using namespace std;
int main(int argc, char **argv) {
int a=5;
int *p,*q;
*p = a;
*q = *p; //line 6
cout<<*p<<p<<*q<<q;
return 0;
}
This program hangs. It seems the problem is on line 6. Why is that?
Yes, those are dangling pointers and you're running into undefined behaviour.
You can't dereference a pointer that points to memory you don't own:
int* p;
*p; //illegal
int* x = NULL;
*x; //illegal
int* y = new int;
*y; //OK!
A correct version would be:
int main(int argc, char **argv) {
int a=5;
int *p = new int;
int *q = new int;
*p = a;
*q = *p; //line 6
cout<<*p<<p<<*q<<q;
delete p;
delete q;
return 0;
}
or
int main(int argc, char **argv) {
int a=5;
int *p;
int *q;
p = &a;
q = p; //line 6
cout<<*p<<p<<*q<<q;
return 0;
}
An even more correct version:
int main(int argc, char **argv) {
int a=5;
int p,q;
p = a;
q = p; //line 6
cout<<p<<p<<q<<q;
return 0;
}
No pointers :)
There's a problem in line 5 too. You have declared pointers but you haven't made them point at anything, that doesn't happen automatically. And dereferencing an uninitialized pointer, as you do, is liable to crash your program.
Something like this would be better.
int main(int argc, char **argv) {
int a=5;
int b, c;
int *p,*q;
p = &b; // make p point at b
q = &c; // make q point at c
*p = a;
*q = *p; //line 6
cout<<*p<<p<<*q<<q;
return 0;
}
The code you have assumes there is something stored at p when there is not.
Is this what you were trying to do?
int a=5;
int *p,*q;
p = &a;
q = p; //line 6
cout<<(*p)<<p<<(*q)<<q;
In the code above, at the end of the program, p and q point to the same address - the address of where the integer a is stored
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With