Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a pointer of a local variable C++

I need to create a function that returns a pointer to an int.

Like so:

int * count()
{
    int myInt = 5;

    int * const p = &myInt;

    return p;
}

Since a pointer is simply an address, and the variable myInt is destroyed after this function is called. How do I declare an int inside this method that will keep a place in the memory in order for me to access it later via the returned pointer? I know I could declare the int globally outside of the function, but I want to declare it inside the function.

Thanks in advance for any help!

like image 838
user906357 Avatar asked Sep 27 '13 04:09

user906357


People also ask

Can you return a pointer to a local variable?

The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.

Can we return local pointer in C?

In C/C++, it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns. So to execute the concept of returning a pointer from function in C/C++ you must define the local variable as a static variable.

What is the return type of pointer in C?

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.

Why should one never return a pointer to something that is stack allocated?

Because it will cause undefined behavior in your program. Show activity on this post. If you return a pointer to a local variable once the function returns it is out of scope. From then on it is undefined behavior if you access the returned pointer.


1 Answers

If you want to return a pointer of a variable correctly you have to do something like.

int * myInt = new int(5);

This is not a local variable BTW, meaning it does not have automatic storage and you have to delete the memory yourself

However using pointers like this is generally unnecessary and unadvised. It's better to create an int outside the function and have the function take a reference.

void count(int & i)
{
    i = 5;
}

BTW I don't know how you are planning to use the variable but since you also suggested using a global variable you may want to use a static var which @JonathanPotter suggested first. In many ways a static variable is similar to a global variable (both have static storage durations)

like image 190
aaronman Avatar answered Sep 20 '22 14:09

aaronman