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++ ?
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.
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 .
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.
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.
For C++, you can use a smart pointer to enforce the ownership transfer. auto_ptr
or boost::shared_ptr
are good options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With