# include<stdio.h>
# include<stdlib.h>
void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}
int main(void)
{
int *p;
fun(p);
*p = 6;
printf("%d\n",*p);
free(p);
return(0);
}
In vs code this shows error because int *p is uninitialized and tells me to initialize the variable ‘p’ to NULL to silence this warning. But when I did that it compiled but showed segmentation fault, likely because I’m assigning 6 to the null address, so how do I fix this?
>Solution :
This function
void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}
changes its own local variable (parameter) a
. That is the function deals with a copy of the value of the passed pointer p
int *p;
fun(p);
The pointer p
stays unchanged and uninitialized.
To make the program correct you need to change the code the following way
void fun(int **a)
{
*a = (int*)malloc(sizeof(int));
}
//...
int *p;
fun( &p);
Though in this case it would be better to declare and define the function like
int * fun( void )
{
return malloc(sizeof(int));
}
//...
int *p = fun();
if ( p )
{
*p = 6;
printf("%d\n",*p);
}
free(p);