开发者

Pointer assignment Problem

When i run the above program in gcc complier(www.codepad.org) i get the output as Disallowed system call:开发者_运维百科 SYS_socketcall Could anyone please clear why this error/output comes?

int main() {
    int i=8;
    int *p=&i;
    printf("\n%d",*p);
    *++p=2;
    printf("\n%d",i);
    printf("\n%d",*p);
    printf("\n%d",*(&i+1));
    return 0;
}

what i have observed is i becomes inaccessible after i execute *++p=2;WHY?


When you do *p = &i, you make p point to the single integer i. ++p increments p to point to the "next" integer, but since i is not an array, the result is undefined.


What you are observing is undefined behavior. Specifically, dereferencing p in *++p=2 is forbidden as i is not an array with at least two members. In practice, your program is most likely attempting to write to whatever memory is addressed by &i + sizeof(int).


You are invoking undefined behaviour by writing to undefined areas on the stack. codepad.org has protection against programs that try to do disallowed things, and your undefined behaviour program appears to have triggered that.

If you try to do that on your own computer, your program will probably end up crashing in some other way (such as segmentation fault or bus error).


The expression*++p first moves the pointer p to point one int forward (i.e. the pointer becomes invalid), then dereferences the resulting pointer and tries to save the number 2 there, thus writing to invalid memory.

You might have meant *p = 2 or (*p)++.


Your code accesses memory it does not own, and the results of that are undefined.

All your code has the right to do as it is currently written is to read and write from an area memory of size sizeof(int) at &i, and another of size sizeof(int*) at &p.

The following lines all violate those constraints, by using memory addresses outside the range you are allowed to read or write data.

*++p=2;

printf("\n%d",*p);
printf("\n%d",*(&i+1));


Operator ++ modifies its argument, so the line *++p=2; assigns 2 to a location on the stack that probably defines the call frame and increments the pointer p. Once you messed up the call frame - all bets are off - you end up in corrupt state.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜