samedi 3 octobre 2015

Why does the print statement change the value of pointer?

I wrote a c++ code like this:

#include <iostream>
using namespace std;

int main() {
    int i = 2;
    int i2 = 0;
    void *pi = &i - 1;
    cout << "by cout - the value of *pi is: " << *(int*)pi << endl;
    printf("by printf - the value of *pi is: %d\n", *(int*)pi);
    printf("the address of pi is: %p\n", pi);
    printf("the address of i2 is: %p\n", (void*)&i2);
    printf("the value of i2 is: %d\n", i2);
    return 0;
}

and the output is:

by cout - the value of *pi is: 0
by printf - the value of *pi is: 0
the address of pi is: 0029fe94
the address of i2 is: 0029fe94
the value of i2 is: 0


now if I remove the statement which will print the address.

#include <iostream>
using namespace std;

int main() {
    int i = 2;
    int i2 = 0;
    void *pi = &i - 1;
    cout << "by cout - the value of *pi is: " << *(int*)pi << endl;
    printf("by printf - the value of *pi is: %d\n", *(int*)pi);
    // printf("the address of pi is: %p\n", pi);
    // printf("the address of i2 is: %p\n", (void*)&i2);
    printf("the value of i2 is: %d\n", i2);
    return 0;
}

now the output is:

by cout - the value of *pi is: 2004212408
by printf - the value of *pi is: 2004212408
the value of i2 is: 0

notice that the value was totally different.

update: If I add some assignment after the print:

#include <iostream>
using namespace std;

int main() {
    int i = 2;
    int i2 = 0;
    void *pi = &i - 1;
    cout << "by cout - the value of *pi is: " << *(int*)pi << endl;
    printf("by printf - the value of *pi is: %d\n", *(int*)pi);
    // printf("the address of pi is: %p\n", pi);
    // printf("the address of i2 is: %p\n", (void*)&i2);
    pi = &i2;
    printf("the value of i2 is: %d\n", i2);
    return 0;
}

the output been normal again:

by cout - the value of *pi is: 0
by printf - the value of *pi is: 0
the value of i2 is: 0

use "g++ -std=c++11 -pedantic -Wall" to compile, version is 4.9.2.

Why could that happen?

Aucun commentaire:

Enregistrer un commentaire