You passed the variable check
to the function foo
by reference through a pointer to it
int check=5;
foo(&check);
So dereferencing the pointer you could get a direct access to the variable check and could change it like
*check= 9;
However within the function you reassigned the pointer with a new address of a dynamically allocated memory
check= malloc(sizeof(int));
So now the pointer check
doe not point to the original object passed to the function by reference. As a result this statement
*check= 9;
changes the dynamically allocated object of the type int
instead of changing the variable passed to the function by reference.
Edit: malloc is deleted now it gives me Segmentation fault (core
dumped) error
It is a bad idea to change such dramatically the code in the question because it will only confuse readers of the question and answers. Neither segmentation fault should occur. It seems the new provided code in the question does not correspond to the actual code that generates a segmentation fault.
Here is a demonstrative program. It compiles and runs successfully.
#include <stdio.h>
void foo ( int *check )
{
*check = 9;
printf( "Inside foo check = %d\n", *check );
}
int main(void)
{
int check = 5;
printf( "Before foo check = %d\n", check );
foo( &check );
printf( "After foo check = %d\n", check );
return 0;
}
The program output is
Before foo check = 5
Inside foo check = 9
After foo check = 9