-
-
Save asgrim/1d6599c7cd28bee859b4 to your computer and use it in GitHub Desktop.
#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; | |
} |
I'm not getting a segfault here. But I think the following is happening:
int *ptr
is a pointer to an int
, which you initialize to the address of v
. 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 case v
. Line 15 should print nicely V is 15\n
.
ptr++;
increases the pointer to the next integer (it increases the pointer with sizeof(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.
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 :)
Q1) From what I understand, I am getting a segfault because I am accessing memory that has not been allocated by my program, is that right?
Q2) if that is correct, then surely it should segfault when trying to assign *ptr (on L13), not when accessing it (on L17) ?