Why does the print statement change the value of a pointer?

I wrote C ++ code as follows:

#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 output:

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 delete the statement that 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 output:

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

Please note that the meaning was completely different.

update: If after printing add the following task:

#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 was 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 4.9.2.

Why could this happen?

+4
source share
2 answers

Access to piis undefined behavior due to the fact that the &i - 1pointer value may not be a valid value.

In the standard (from the C ++ standard) in Β§5.3.1 / 3 we have:

[...] (5.7) (5.9, 5.10) , , , T.

Β§5.7/4:

, , , . , , , . [...] , ; undefined.

+8

, , undefined. .

? - , , .

, i2 i . . , i2 , (&i2 " " ), , , . !

, , .

++ - . , . ++ , undefined: , , , ; , undefined, , .

+4

Source: https://habr.com/ru/post/1610098/


All Articles