PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 27, 2022

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

 April 27, 2022     c++, g++, warnings     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing