简体   繁体   中英

Address of stack memory returned when overloading operator [ ]

I'm encountering some issues with overloading the [] operator for a problem in class. This is the function for the overloading:

const char* Person::operator[](const char* str)
{
    if (strcmp(str, "name") == 0)
        return reinterpret_cast<const char *>atoi(name);

    if (strcmp(str, "age") == 0)
    {
        char temp[4];
        _itoa(age, temp, 10);
        //cout << temp;
        return temp;
    }
}

The class defition looks like this

class Person
{
private:
    const char* name;
    unsigned int age;
    double height;
    int gradeNo;
    int grades[10];
public:
    Person();
    Person(const char* name, int age, double height);
    void addGrade(int grade);
    const char* operator [] (const char* str);
    operator int();
};

The problem I'm getting is with the return temp; line from the operator overload function. CLion returns the following warning: Address of stack memory associated with local variable 'temp' returned

Sure enough, when trying to use the operator, the value returned is a memory address. How can I go about fixing this? Is it related to the return type of the function?

You are taking an address to a temporary (that is located on the stack), that will leave the returned pointer dangling almost immediately.

I would very strongly suggest using std::string for strings, do not write C++ just as C with classes.

Then return by std::string by value here. Bad C-like alternative is to allocate the string on the heap and return that, preferably as std::unique_ptr at least.

EDIT after the comment below:

Since you are required to convert an integer to string and return the value, you cannot return a temporary variable, the result must outlive the method. There are basically two bad options:

  1. Make temp static, this way the pointer remains valid. Downside is the function is no longer re-entrant. This is safer because it won't leak.
const char* foo(int age){
    static char temp[4];
    _itoa(age, temp, 10);
    return temp;
}
  1. Return a heap allocated string. Big danger is that you are leaving the user to deallocate it:
const char* foo(int age){
    char* temp = new char[256];
    _itoa(age, temp, 10);
    return temp;
}

I believe you also have a typo in your code:

return reinterpret_cast<const char *>atoi(name);

The atoi should not be there, right? reinterpret_cast should not be needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM