Returning pointer from a function

128,819

Solution 1

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

Solution 2

Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:

int *fun()
{
    int *point;
    *point=12;  <<<<<<  your program crashed here.
    return point;
}

The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.

Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.

int *fun()
{
    int point;
    point = 12;
    return (&point);
}

or almost identically:

int *fun()
{
    int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:

int *fun()
{
    static int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

or

int *fun()
{
    static int point;
    point = 12;
    return (&point);
}

As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.

Share:
128,819
user567879
Author by

user567879

Updated on September 30, 2020

Comments

  • user567879
    user567879 over 3 years

    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;
    }   
    
  • user567879
    user567879 over 12 years
    If have more than one values to store, what would I do? Whether I need to allocated all or I can just increment the pointer?
  • cnicutar
    cnicutar over 12 years
    @user567879 You need to malloc more space. Something like int *point = malloc(num_values * sizeof *point);
  • tremendows
    tremendows almost 11 years
    Also int *point = calloc(num_values,sizeof(int)) will be useful. More info at thinkage.ca/english/gcos/expl/c/lib/calloc.html
  • Christian Gollhardt
    Christian Gollhardt almost 10 years
    Never have developed in C but isn't new for C++?
  • idleHands_94
    idleHands_94 almost 10 years
    That is correct; however, I have found that new and delete have in fact worked with memory management in C.
  • Mahesha Padyana
    Mahesha Padyana almost 9 years
    Is it a good practice to return pointer from a function and make the main program to free the memory? Any other alternative to this? (only in case it is not a good practice)
  • Destructor
    Destructor over 8 years
    @cnicutar: It would be better if u cast the result of malloc (to int*) although it isn't necessary in C,
  • hgiesel
    hgiesel almost 8 years
    This is simply not correct. C doesn't have the keywords new or delete.
  • Pantelis Sopasakis
    Pantelis Sopasakis almost 7 years
    @cnicutar According to tutorialpoint.com, it is not a good idea to return a pointer to a local object in a function. There, they give an example where the local variable is an array (stack allocation). Is it safe to allocate memory with malloc/calloc and return a pointer? As a side note, I have never experienced trouble with this practice and neither gcc nor valgrind have ever given me warnings or errors.
  • cnicutar
    cnicutar almost 7 years
    @PantelisSopasakis It depends on the storage class of the object to which the pointer points. If the object has "auto" storage and gets freed automatically when it goes out of scope then it's unsafe to return a pointer. But if you malloc'd the memory or if the object has "static" storage a pointer is fine. It might still be morally dubious to return memory allocated using malloc because then you force the caller to depend on an implementation detail and free it.
  • scape
    scape over 6 years
    Doesn’t 12 exist only on the stack of that function call? That seems like it would produce undefined behavior
  • C--
    C-- over 5 years
    And free() it after use.
  • Admin
    Admin almost 5 years
    Will using static cause compilation warnings?