skip to Main Content
#include<iostream>

int* function() {
    int a = 2;
    return &a;
}

int main() {
    int* b = function();
    *b = 3;
    return 0;
}

I was trying to run this program, but this is supposed to give me an error because a should be deleted after leaving the function. However, I received no error in Visual Studio 2022. a is not even a static variable, nor is b constant.

I tried to copy and paste this code in different compilers to see if the lecture was wrong, but I recieved

main.cpp:4:16: warning: address of local variable ‘a’ returned [-Wreturn-local-addr]

like what it is supposed to be.

3

Answers


  1. There are two possible causes:

    1. function() returns NULL, so the following assignment to b is an undefined behavior.
    2. function() returns the address of a in the function stack, so the assignment to b is indeed "valid".
    Login or Signup to reply.
  2. You are returning a local variable’s address, which will cause undefined behavior for a is no longer available(or, lifetime is over) after return.

    To return a, you should declare a as a pointer and allocate memory for it.

    int* function() {
        int* a = new int;
        *a = 2;
        return a;
    }
    
    int main() {
        int* b = function();
        *b = 3;
    
        delete b; // don't forget to free
    
        return 0;
    }
    

    This should work fine.

    The compiler will only point out your problem with a warning, but it will not throw an error. You can see that compiler wants to tell you in -Wreturn-local-addr.

    Login or Signup to reply.
  3. I was trying to run this program, but this is supposed to give me an error because a should be deleted after leaving the function.

    The function returns &a, and since a goes out of scope after the function returns (as a is declared on the stack), &a is dangling. The compiler sees this and warns you about that, but it doesn’t error since there technically isn’t anything wrong with returning an pointer, just as there isn’t an issue with returning nullptr.

    BTW: "Errors" and "warnings" in C++ are completely different things. Errors cause compilation to fail (such as syntax errors), while warnings notify you about potential fail points but allow the code to compile.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search