What would be the values after performing this operation?
#include <stdio.h>
int main() {
int *a = 0;
int *b = 3;
*a = *b ;
printf("%d", a);
printf("%d", b);
return 0;
}
The code above gives me a segmentation fault.
CodePudding user response:
*a = *b
(what does it mean, how it works)
*a = *b ;
means
*(a ) = *(b );
x
increments x
and returns the original value. So the following is equivalent:
*a = *b; // Copy the `int` to which `b` points into the `int` to which `a` points.
a = a 1; // Make `a` point to the following `int`.
b = b 1; // Make `b` point to the following `int`.
Before: After:
a a
---------- ---------- ---------- ----------
| ---------->| x | | ------ | p |
---------- ---------- ---------- | ----------
| y | --->| y |
---------- ----------
| | | |
b b
---------- ---------- ---------- ----------
| ---------->| p | | ------ | p |
---------- ---------- ---------- | ----------
| q | --->| q |
---------- ----------
| | | |
The code above gives me a segmentation fault.
You assigned garbage to a
and b
. 0
as a pointer is the NULL pointer, and 3
isn't a valid pointer.
CodePudding user response:
Given
#include <stdio.h>
int main() {
int *a = 0;
int *b = 3;
*a = *b ;
printf("%d", a);
printf("%d", b);
return 0;
}
the printed values can not be predicted as the code invokes undefined behavior in multiple ways.
First, both *a
and *b
invoke undefined behavior by dereferencing invalid pointers - a
is initialized to a null pointer value, and b
is initialized to point to address 3
, which is almost certainly invalid also.
Second,printf("%d", a);
invokes undefined behavior by trying to print an int *
variable with the %d
format specifier for int
. The proper code would be
printf("%p", ( void * ) a);
It's not clear what the currently-posted code is supposed to do.