简体   繁体   中英

segmentation fault in this pointers program in C

I keep getting a segmentation fault (core dumped) message whenever I try to run this C program.

#include <stdio.h>

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

It didn't have any r s at first but I had to add r s as an alias to i and then Add print statements to output the dereferenced values of q and r .

In your code

p,r = &i;

does not assign p , it leaves p uninitialized. Next, the very moment you dereference p (and q also, as it was assigned with the value of p ) you hit undefined behavior , as you're dereferencing invalid memory.

You need to use

p = r = &i;

Compile your code with proper warnings enabled and, with your code, you should see something similar to

warning: left-hand operand of comma expression has no effect [-Wunused-value]

  p,r = &i; ^ 

Use this:

p = &i;
r = &i;

instead of

p,r = &i;

Uninitialized pointer is bad.

//I write that as an answer because i still don't have 50 reputation

1: I didn't understand what do you want that the program will do. the use of q and r is useless.

2: p,r=&i; is not a good command. use p=r=&i or p=&i; r=&i; p=&i; r=&i; or p=&i; r=p; p=&i; r=p;

i have made the correction in your code and it is working fine please have look into it.

`#include <stdio.h>

int main()
{
    int i = 200, *p, *q, *r;
    p = &i;
    r = &i;    
    q = p;
    *q = *p + 1;
    printf("*p = %d\n", *p);
    printf("*r = %d\n", *r);
    return 0;
}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM