简体   繁体   中英

char array initialization and destructor

First of all, I was not using C++ for a lot time and it is possible that this question is very easy and it does not deserve to be posted here. Anyway, I did not found any solution here or in other source. My problem consists in following. Let's assume we have class A :

Class A
{
    char* string;
public:
    char*& getString(){ return string; }
    ~A() 
    { 
        if (string)
            delete[] string; 
    }
};

I cannot modify this class(it is just a sample of the real class). I want to set field string to a value:

int main()
{
    A a;
    a.getString() = new char[3];
    a.getString() = "Hi\0";
    return 0;
}

This code cause Debug Assertion Fail when destructor ~A() is called. What I'm doing wrong here? I really will appreciate any suggestion about what I'm doing wrong.

EDIT: It seems, that assignment operator here is important. Actually, I'm doing such an assignment:

int main()
{
    A a;
    char name[256];
    std::cin.getline(name, 256);

    a.getString() = new char[strlen(name)];
    //actual version
    strcpy_s(a.getString(), strlen(name), name);
    //a.getString() = "Hi\0";
    return 0;
}

This code cause Debug Assertion Fail when destructor ~A() is called. What I'm doing wrong here?

 a.getString() = "Hi\\0";

After this line, a.string points to a string literal. The destructor will then call delete[] on the pointer. Deleting a string literal has undefined behaviour. Also, the previously allocated dynamic array is leaked, since the pointer was overwritten.

The solution is to remove the quoted line.

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