I wrote this code. In the main you see x a pointer to an integer. The function val allocates a storage space of an int , stores the value n in it and return the adress of the int allocated.
In the function val2 , i pass by value x , but when i execute val on x (x here is the copy of the original) inside the function val2 , i find that the value of *x in the main changes. Isnt any change on the x inside the function val2 local ?
#include <stdio.h>
#include <stdlib.h>
int * val(int * x , int n)
{
int * d;
d = (int *)malloc(sizeof(int));
*d = n;
return (d);
}
void val2 (int * x ,int n)
{
x = NULL;
x = val(x , n);
}
int main()
{
int * x = NULL;
x = val (x , 2);
printf("\n after executing val \n");
printf(" The value of *x = %d\n" , *x);
printf("The adress x contains %p\n " ,x);
free(x);
val2(x , 7);
printf("\n after executing val2 \n");
printf(" The value of *x = %d\n" , *x);
printf("The adress x contains %p\n " ,x);
return 0;
}
I get *x = 2 The *x = 7 Can someone here expalin how *x changed in the context of the function and thanks y'all <3 Edit : I copied this from the compiler :
after executing val The value of *x = 2 The adress x contains 0xb6403068 after executing val2 The value of *x = 7 The adress x contains 0xb6403068 [Process completed - press Enter]
CodePudding user response:
free(x)
releases the memory pointed to by x
. After that, the C implementation may use the memory for any other purpose.
When the main
routine later uses that memory, by attempting to print *x
, the behavior of the program is not defined by the C standard. Even using the value of a pointer after the memory it points to is freed results in the behavior not being defined by the C standard.
What likely happens is that, for the malloc
in the call to val
inside val2
, the C implementation reuses the memory that was freed earlier. Thus, this call to val
puts 7 in that memory. And then, in main
, since x
is still pointing to that memory (even though the C standard does not require this), accessing it with *x
fetches the 7 from memory.
When the program is compiled with optimization or is compiled by another compiler or contains additional code that complicates the situation, this behavior is likely to change, because it is not behavior controlled by the C standard.
CodePudding user response:
You explicitly said to replace 'x' with the return value from 'val'
x = val (x , 2);
'val' returns its 'd', so that overwrites mains 'x'