简体   繁体   中英

Why am I getting a memory exception on deleting a char*

I am attempting to write my own string class (so I can learn more) and while doing so I noticed I ran into an issue with how the char data is being deleted, when the program closes the destructor of string will be called and there will be a heap error on deleting the data

#include <string.h>

template<typename T>
class String
{
protected:
    T* mData;

public:
    String(const T* data);
    ~String();
};

template<typename T>
String<T>::String(const T* data)
{
    if(data != NULL)
    {
        mData = new T[strlen(data)];
        strcpy(mData, data);
    }
}

template<typename T>
String<T>::~String()
{
    if(mData != NULL)
    {
        delete [] mData;
        mData = 0;
    }
}

int main(void)
{
    String<char> Test("Test");

    return(0);
}
 mData = new T[strlen(data)];
        strcpy(mData, data);

You are allocating one item too few, strcpy copies the nul terminating byte as well as the string

You should use "memcpy" and "memset" functions instead of that like strcpy:

http://www.cplusplus.com/reference/clibrary/cstring/memcpy/

You must be careful about operator new throwing an exception in your constructor. If that happens, you must make sure you have initialized your data pointer to nullptr, otherwize, the destructor will be called and try to delete some random address.

#include <cstring>

template<typename T>
class string {
    protected:
        T * data_;
    public:
        string(T const * data);
        ~string();
};

template<typename T>
string<T>::string(T const * data)
try {
    if(!data) data_ = 0;
    else {
        data_ = new T[std::strlen(data) + 1];
        std::strcpy(data_, data);
    }
} catch(...) {
    data_ = 0;
}

template<typename T>
string<T>::~string() {
    delete[] data_;
}

int main() {
    string<char> test("test");
    return 0;
}

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