Wednesday, April 27, 2022

[FIXED] How to set warning in g++ for warning of returning pointer to local variable?

Issue

I think both of the two functions are problematic because they return reference/pointer to local variable allocated in stack:

int &func1() {
   int a = 3; 
   return a;
}
int *func2() {
    int a = 3;
    int *p = &a;
    return p;
}

but when I use compile command g++ -Wall, why it only gives warning for func1 but not func2? Is it because func2 could be intentionally used for some purpose or the warning could be set by adding other parameter? My g++ version is 4.6.3, on Ubuntu 12.04.


Solution

There is no way for the compiler to know what you are trying to do with the pointer you are returning in func2.

You could as well be returning an instance for an array, for example:

int *func2() {
    int a = 3;
    int *p = &a;
    /*some useful stuff*/
    if (some_criteria)
        p = new int[10];
    return p;
}

Because the compiler does not have the power to evaluate the semantics of the returned pointer.



Answered By - Tércio de Almeida
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.