Heap corruption detected ERROR

  • Hi ,
    I am trying to implement something like the standard c++ string class using cstring functions but I am getting the heap corruption error and debugging didn't help figure it out.My class is declared like this:


    class String

    typedef std::size_t sizetype;
    static const sizetype DEFAULT_CAPACITY=30;
    String(const char initial[]="");


    char *data;
    sizetype usedSpace;



    and the relevant implementation is shown below:


    String::String(const char initial[])

    data=new char[strlen(initial)];


    delete [] data;


    But when i instantiate the class in the main function to test ,like this:

    #include <iostream>
    #include <cstring>
    using namespace std;
    int main()

    String mString1("KARAMAGE");
    String mString2("KAREKEZI");

    cout << mString1.data <<endl;
    cout << mString2.data <<endl;

    return 0;


    The program crashes when the destructor is called (at least the call stack of my degugger is telling me so).I first thought it was a problem with our processor but I am experiencing the same issues on my intel windows8 machine.Am I doing something wrong here ,as I have always declared pointer arrays and deleted them like this.
    I would also appreciate it if you helped run this code through your environment and tell me what your debugger is saying.

    Thanks for your time.

  • Hi,

    One thing I spotted is that the size of your data buffer is wrong in the String constructor, strlen() doesn't count the terminating null character.

    Hope it helps,

  • Thanks mate,
    I had been staring at this piece of code for hours without noticing that !It really helped.


Log in to reply