user3781974 user3781974 - 3 months ago 8
C Question

why this code doesn't print "20"?

void fun(int* x){
x=(int*)malloc(sizeof(int));
*x = 20;
}

int main(){
int y=31;
fun(&y);
printf(%d,y);
}


Why this code succeed to compile anyway?

Comment: it was compiled on Eclipse
I see the problem on line:
x=(int*)malloc(sizeof(int));

why this program didn't crashed at runtime?

Answer

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.

Comments