0

I wrote some code that involves moving and changing variables in C++. Below is what I have wrote.

#include <iostream>

void six(int*& ptr) {
    int s = 6;
    ptr = &s;
}

int main() {
    int f = 5;
    int* ptr = &f;

    std::cout << *ptr << '\n';
    six(ptr);

    if (ptr) {
        std::cout << *ptr;
    }
    else {
        std::cout << "null\n";
    }

    return 0;
}

so this prints:

5
6

I tried another code, adding a single line:

#include <iostream>

void six(int*& ptr) {
    int s = 6;
    ptr = &s;
    free(&s); // added line
}

int main() {
    int f = 5;
    int* ptr = &f;

    std::cout << *ptr << '\n';
    six(ptr);

    if (ptr) {
        std::cout << *ptr;
    }
    else {
        std::cout << "null\n";
    }

    return 0;
}

Obviously, this gives an error after printing 5 because what the modified pointer is pointing is not available when called the second time.

However, I am confused at the first case. When calling six in the main function, variable s is not in the main scope, but the value itself still continues to remain in the memory to be referenced. Doesn't C++ automatically destroy variables and clean them when it goes out of the scope? Is this a memory leak?

anymate98
  • 13
  • 6
  • First code doesn't always act like that. It is undefined behavior. See https://stackoverflow.com/questions/19042552/returning-a-pointer-of-a-local-variable-c. Also You can't free automatic variable. `free(&s);` is nonsence. – openingnow Dec 13 '19 at 06:45
  • @openingnow Thanks for the comment, but I am not talking about whether the code is right or not. Both had no problems with compiling. – anymate98 Dec 13 '19 at 06:48
  • It *does* compiles, but causes error. – openingnow Dec 13 '19 at 06:48
  • @openingnow Yes, and I already wrote that it produced an error. What I am curious about is the behavior from the first case. – anymate98 Dec 13 '19 at 06:50
  • It *can* have six in memory which is not guaranteed. If you run first code at https://www.onlinegdb.com/ with `-O3` flag, value is changed. – openingnow Dec 13 '19 at 06:51
  • See https://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable – juanchopanza Dec 13 '19 at 06:54
  • @openingnow I tried my code in VS2019. Also tried it in onlinegdb.com, too. Maybe this is a problem with a compiler? – anymate98 Dec 13 '19 at 07:01
  • No, it's just an undefined behavior. C++ spec doesn't clarify whether destroyed value is actually removed from memory. – openingnow Dec 13 '19 at 07:03
  • @openingnow Got it. – anymate98 Dec 13 '19 at 07:07

1 Answers1

2

The first case is not a memory leak, but an undefined behaviour because your variable go out of scope.

In this case you don't know when the memory will be cleaned(replaced) o reallocated.

So in some case the result can be correct but it's a pure question of luck.

Zig Razor
  • 3,381
  • 2
  • 15
  • 35