Last active
August 29, 2015 14:16
-
-
Save asgrim/1d6599c7cd28bee859b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
int v; | |
int *ptr = &v; | |
*ptr = 15; | |
ptr++; | |
ptr++; | |
*ptr = 10; | |
cout << "V is " << v << endl; | |
cout << "ptr " << ptr << endl; | |
cout << " is " << *ptr << endl; | |
return 0; | |
} |
Q1) right
Q2) should is not the correct term, what you have here is an undefined behaviour, nothing is specified on what should happen in this case.
Thank you both :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not getting a segfault here. But I think the following is happening:
int *ptr
is a pointer to anint
, which you initialize to the address ofv
. Both these variables are located on the stack.Doing
*ptr = 15
, actually tells that you store 15 on the integer where ptr is pointing at, in this casev
. Line 15 should print nicelyV is 15\n
.ptr++;
increases the pointer to the next integer (it increases the pointer withsizeof(int *)
, which is 4 in my case, but could be 8 if you run on 64bit I guess). And you do this twice.The problem is, is that now you are not pointing to the initial v, but to something else that is 2 integers above on the stack, which most likely is some information about returning back from the code that is calling your
main
function.Without seeing the segfault details, I guess the problem is not so much that it segfaults on line 17, but that it segfaults because it jumped back with corrupted information, as you destroyed the calling parameters to
main
.[edit] The actual address on where to return to is 5 positions back, so that is not the one you are overwriting. [/edit]
So, in a nutshell:
Q1: sort of, it IS allocated (it's the stack), but you're not allowed to touch it, since at that place it contains information about returning from the main function, arguments etc).
Q2: I don't get the segfault (not on both 32 and 64bit). It might depend on the compiler.