Haider
Haider

Reputation: 25

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 rs at first but I had to add rs as an alias to i and then Add print statements to output the dereferenced values of q and r.

Upvotes: 0

Views: 86

Answers (4)

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;
}`

Upvotes: 0

Roy Avidan
Roy Avidan

Reputation: 768

//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; or p=&i; r=p;

Upvotes: 0

msc
msc

Reputation: 34658

Use this:

p = &i;
r = &i;

instead of

p,r = &i;

Uninitialized pointer is bad.

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

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;
  ^

Upvotes: 6

Related Questions