Reputation: 25
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
.
Upvotes: 0
Views: 86
Reputation: 7
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
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
Reputation: 34658
Use this:
p = &i;
r = &i;
instead of
p,r = &i;
Uninitialized pointer is bad.
Upvotes: 1
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