1

My professor had me copy and paste the code below she wrote, and it kept on giving me bugs.

By running her program, the output was 1 for any value.

Logically, I understand how the function should return the address and in the main it prints the value of it. Theoretically, that is.

So here's what I tried so far:

  1. Simply removing the statement p = cube(&n) and replacing with:

    std::cout << "Cube of " << n << " is " << cube(&n) << std::endl;
    

    This worked.

  2. In order to solve the "local variable" error, I made 'result' a global variable.

  3. In cube(), I did:

    int *cube(int *number)
    {
        int result = (*number) * (*number) * (*number);
        int *newResult = &newResult;
        return newResult;
    }
    

    ...but it outputted 1 for any integer.

This is the code sample she shared.

#include <iostream>

int *cube(int *);

int main()
{
    int n, *p;
    std::cout << "Enter an int: ";
    std::cin >> n;

    p = cube(&n);

    std::cout << "Cube of " << n << " is " << *p << std::endl;

    return 0;
}

int *cube(int *number)
{
    int result = (*number) * (*number) * (*number);
    return &result;
}

According to her, the output of this program should be the cube of the inputted integer. For example, 3 in -> 27 out.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ariyon
  • 21
  • 1
  • 6
  • There is no reason to use pointers here. If you do want to return a pointer, either use address of existing variable or create `new int`, set its value, work with it, and then `delete` it. –  Apr 16 '19 at 23:48
  • 1
    Her code returns a pointer to a part of the stack that becomes undefined once you return from the function. Like @dyukha says if you want to return a pointer from this function it should be to something on the heap (created using new()) not the stack. – Dave S Apr 16 '19 at 23:59
  • This looks like a mega duplicate. What is the canonical question for returning references/pointers from a function to things on the stack? It must have been asked in 2008. Some leads: *[Returning pointer from a function](https://stackoverflow.com/questions/7754986/)* (C, 2011) and *[Using C-string gives Warning: "Address of stack memory associated with local variable returned"](https://stackoverflow.com/questions/18041100/)* (2013) – Peter Mortensen Oct 22 '22 at 04:43
  • Related (but none of the answers deal with this problem): *[What and where are the stack and heap?](https://stackoverflow.com/questions/79923/)* – Peter Mortensen Oct 22 '22 at 04:47
  • Tagged with both C and C++... - *[Return pointer to data declared in function](https://stackoverflow.com/questions/2320551/return-pointer-to-data-declared-in-function)* – Peter Mortensen Oct 22 '22 at 04:53
  • This is used a duplicate target for C++ questions: *[C++ Returning reference to local variable](https://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable)* (2011, five answers and 137 upvotes). – Peter Mortensen Oct 22 '22 at 04:54
  • Even higher scored (the same fundamental problem): *[Returning an array using C](https://stackoverflow.com/questions/11656532/)* (2012, 12 answers, and 196 upvotes) – Peter Mortensen Oct 22 '22 at 05:08

3 Answers3

1

You are trying to return a local reference that cannot be accessed outside of it declaration scope. You need to allocate memory on the heap using the new keyword and not the stack. Check out the difference here.

int* cube(int number)
{
    return new int (number * number * number);
}

Note that I pass number by value and not by reference as there is no obvious speed performance/need to modify the value of the passed in variable. I also do not bother making an intermediate variable, newResult, as the result of new can just be returned. Do keep in mind that if I were to create an intermediate value newResult, it would be of type int*. Do NOT forget to give back the memory when you no longer need the result. Use the delete keyword to deallocate the memory. All of that being said, do not bother returning a pointer as use of heap is slow and manual memory allocation is messy.

Below is what you should use.

int cube(int number)
{
    return number * number * number;
}

Creating a static and global variables should be used with care as they will use more memory.

Passing a primitive variable by reference is also not advisable read Reasons to not pass simple types by reference?.

void cube3(int &number)
{
   number = (number) * (number) * (number);
}
user10447655
  • 180
  • 2
  • 10
0

It is about a scope of variables.

1. Global variable.

The 'result' is a local variable that can not be accessed or used outside { and } block. You can use it by a global variable.

The global variables are declared at the top of the program outside all of the functions or blocks.

static int result;
void cube(int *number)
{
    result = (*number) * (*number) * (*number);
}

In C, you can pass parameters to a function by pointers.

void cube2(int *number)
{
    *number = (*number) * (*number) * (*number);
}

2. Pass by reference.

In C++, you can pass parameters to a function either by pointers(cube2) or by reference code blow:

void cube3(int &number)
{
   number = (number) * (number) * (number);
}

In a main function:

int main()
{
    int input_num, n;
    std::cout << "Enter an int: ";
    std::cin >> n;

    input_num = n;
    cube(&n);

    std::cout << "Cube of " << input_num << " is " << result << std::endl;

    cube2(&n);
    std::cout << "Cube of " << input_num << " is " << n << std::endl;

    n = input_num;
    cube3(n);
    std::cout << "Cube of " << input_num << " is " << n << std::endl;

    return 0;
}
tommybee
  • 2,409
  • 1
  • 20
  • 23
-1

result is a local variable and allocated on the stack. When that function ends that memory owned by result is no longer valid. Therefore any pointer to that memory is not valid.

For a function that simple there's no need to bother with pointers. Just return a copy of the result by value.

int cube(int *number)
{
    int result = (*number) * (*number) * (*number);
    return result;
}
sashang
  • 11,704
  • 6
  • 44
  • 58