Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer assignment Problem

Tags:

c

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?

like image 715
sudhansu Avatar asked Aug 19 '26 12:08

sudhansu


2 Answers

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.

like image 133
casablanca Avatar answered Aug 21 '26 02:08

casablanca


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).

like image 20
Derrick Turk Avatar answered Aug 21 '26 03:08

Derrick Turk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!