Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning pointer from a function

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; }    
like image 798
user567879 Avatar asked Oct 13 '11 13:10

user567879


1 Answers

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);              ^ 
like image 51
cnicutar Avatar answered Sep 18 '22 19:09

cnicutar