I am trying to return pointer from a function. But I am getting segmentation fault. Someone please tell what is wrong with the code
#include<stdio.h>
int *fun();
main()
{
int *ptr;
ptr=fun();
printf("%d",*ptr);
}
int *fun()
{
int *point;
*point=12;
return point;
}
Allocate memory before using the pointer. If you don't allocate memory *point = 12
is undefined behavior.
int *fun()
{
int *point = malloc(sizeof *point); /* Mandatory. */
*point=12;
return point;
}
Also your printf
is wrong. You need to dereference (*
) the pointer.
printf("%d", *ptr);
^