0

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.

Claudio Cortese
  • 1,372
  • 2
  • 10
  • 21
Haider
  • 25
  • 1

4 Answers4

6

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;
  ^
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Use this:

p = &i;
r = &i;

instead of

p,r = &i;

Uninitialized pointer is bad.

msc
  • 33,420
  • 29
  • 119
  • 214
  • `Uninitialized pointer is undefined behavior.` without proper context, this is rubbish. How about `int *p; p = NULL;`. `p` was unitialized, was not it? – Sourav Ghosh Feb 17 '17 at 11:52
  • especially an uninitialized pointer is NOT undefined behavior. Dereferencing one is. – Kami Kaze Feb 17 '17 at 12:33
0

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

Roy Avidan
  • 769
  • 8
  • 25
  • the second point is not true `p,r=&i;`is a valid command, it just doesn't do anything with p. Plus what you said is already covered by sourav (an hour before) so you don't add anything. – Kami Kaze Feb 17 '17 at 13:14
0

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