user3781974 user3781974 - 2 months ago 5
C Question

why this code doesn't print "20"?

void fun(int* x){
*x = 20;

int main(){
int y=31;

Why this code succeed to compile anyway?

Comment: it was compiled on Eclipse
I see the problem on line:

why this program didn't crashed at runtime?


There is nothing wrong with the code syntactically, so it compiles.

The address of y is passed to the function. the pointer x in the function which holds the address of y, is overridden by an address of valid memory allocated by malloc. An int is written there and not into y as the value of the pointer was changed. Then the function returns (the allocated memory in fun does 'leak').

The value of y in the main stays unchanged.

The behavior of this program is defined.