segmentation Fault - Pointers

Why do I get a segmentation fault?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main () {

int x = 5;

int *a;
int *b;

*a = x;
b = &x;

cout << "a's address is " << a << endl;
cout << "b's address is " << b << endl;

cout << "a's value is " << *a << endl; // Segmentation fault here
cout << "b's value is " << *b << endl; // Segmentation fault here

return 0;
}
Last edited on
'a' is a pointer to an int, but is not initialized. When you dereference it in line 11, you assign the value of x (5 in this case) to some unknown location in memory.
Makes sense, but then why does line 18 also give me a segmentation fault?
I commented out line 17 and it still complains about a segmentation fault.
Writing to unknown memory can have weird consequences. If you clobbered the program counter or something, you never know what you'll get.

Try commenting out line 11 (and 14 and 17) and see if line 18 is ok then.

Or better yet, change 8 to int *a = new int;. That should take care of the problem.
Last edited on
GOT IT! THANKS :)
Topic archived. No new replies allowed.