Returning pointer from a function

user567879 picture user567879 · Oct 13, 2011 · Viewed 120.2k times · Source

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;
}   

Answer

cnicutar picture cnicutar · Oct 13, 2011

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);
             ^