1
# 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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Function args are passed by value in C. So `a` is a local variable in the function. Setting it does not change the caller's variable. See duplicate post for more details and suggested fixes. – kaylum Jan 30 '22 at 21:19
  • 1
    Side node: You may want to read this: [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/12149471) – Andreas Wenzel Jan 30 '22 at 21:23

1 Answers1

2

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);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335