Random behavior with Pointer de-referencing in C++

115 views Asked by At

I have the following code:

#include <iostream>
using namespace std;

int main ()
{
    int myvar = 5;
    int * p;
    cout << "Hello2" << endl;

    *p = myvar;
    cout << "Hello" << endl;
    cout << p << endl;
    //cout << &myvar << endl;
}

I know I am not doing the right thing by not initializing the pointer. I was just playing with pointers and noticed this. The issue is when I comment out the last line, the program executes normally. But as soon as I uncomment the line, I get a segmentation fault. I don't know why printing address of myvar is causing this? Has myvar been modified in any way because of pointer dereferencing? I am using C++11.

3

There are 3 answers

4
David G On
int* p;
*p = myvar;

You are creating an uninitialized pointer and then derferencing that pointer. This has undefined behavior because p has to point to something for it to be derferenced correctly. Therefore your program's behavior can't be reasoned with.

0
michel9501 On

Segmentation Fault occurs when trying to access a virtual memory address that has no read permissions.

In your case, the local variable p holds uninitialized garbage from the stack. you are dereferencing a memory address that might not be readable(e.g no read permissions, hence the segmentation fault when trying to access it).

0
Amadeus On

I'm not entirely sure the purpose of your snippet, but the following code will work, and perhaps it will help:

int myvar = 5;
int *p = nullptr;
p = &myvar;
cout << myvar << endl;
cout << &myvar << endl;
cout << p << endl;
cout << *p << endl;

(Note: I used two lines for setting 'p' because that is how you did it in your snippet. You could easily just use: int *p = &myvar; )

Anyway, there are scope issues here as p will only be valid as long as myvar is in scope; however, this does illustrate the basics of pointers. myvar and *p will return the same value (the value being pointed to), and &myvar and p will return the same value (the location of value in memory.)