_Block_Type_Is_Valid (pHead->nBlockUse) Error

后端 未结 2 1250
猫巷女王i
猫巷女王i 2020-12-14 09:23

I been working in a new project but I encounter with a problem which I can\'t see why fail.

When I perfom this line delete textY give me the error _Block_Type_Is_Val

相关标签:
2条回答
  • 2020-12-14 09:37

    Just use a std::string. That error means that you double deleted something, or something like that, a problem that you wouldn't have if you didn't manage your own memory. Your code is littered with memory leaks and other bugs that you won't have with std::string.

    0 讨论(0)
  • 2020-12-14 09:59

    From what I can see, the error has to do with the default ctor for Text. You take in a char* pointer, allocate space for the string, but don't actually copy the text into str, but simply assign the pointer! You do it correct in the copy ctor though. Now, consider this example:

    class Foo{
    public:
        Foo(char* text){
            str = text;
        }
    
        ~Foo(){
            delete str;
        }
    
    private:
        char* str;
    };
    
    int main(){
        Foo f("hi");
    }
    

    C++03 (for backwards compatability...) allows literal strings ("hi") to bind to non-const char* pointers, as seen in this code. C++11 thankfully fixed that and this should actually no longer compile. Now, deleting a literal string obviously doesn't work, as the string is placed in the read-only section of the .exe and as such isn't deleteable. I guess this is where your error comes from, if you instantiate a Text object from a literal string.

    Note that this also happens if you create it from a char[] created on the stack:

    char text[] = "hi";
    Foo f(text);
    

    as the Foo will now try to delete a stack-object.

    Another case where this might happen is if you double-delete an object:

    char* text = new char[3];
    Foo f(text);
    delete text;
    
    0 讨论(0)
提交回复
热议问题