Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

shows variable uninitialized when calling a function that uses malloc

# 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading