Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return pointer to data declared in function

Tags:

c++

c

pointers

I know this won'T work because the variable x gets destroyed when the function returns:

int* myFunction()
{
    int x = 4; return &x;
}

so how do I correctly return a pointer to something I create within the function, and what do I have to take care with? How do I avoid memory leaks?

I've also used malloc:

int* myFunction2()
{
    int* x = (int*)malloc(sizeof int); *x = 4; return x;
}

How do you correctly do this - in C and C++ ?

like image 515
sp. Avatar asked Feb 23 '10 18:02

sp.


People also ask

How do you return pointers from function?

Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.

Can a pointer be used as a return type for a function?

You can use a trailing return type in the declaration or definition of a pointer to a function. For example: auto(*fp)()->int; In this example, fp is a pointer to a function that returns int .

How do you return a pointer to an array from a function in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

Can a function return a struct pointer?

Definitely not, because the variable defined in the function (in "auto" storage class) will disappear as the function exits, and you'll return a dangling pointer.


1 Answers

For C++, you can use a smart pointer to enforce the ownership transfer. auto_ptr or boost::shared_ptr are good options.

like image 75
Fred Larson Avatar answered Oct 07 '22 19:10

Fred Larson