c++ - Debug Error when invoking destructor with delete -
i have following code :
#include <iostream> using namespace std; class mystring { private: char* buffer; public: mystring(const char* initialinput){ if(initialinput){ buffer = new char[strlen(initialinput + 1)]; strcpy_s(buffer, strlen(initialinput) + 1, initialinput); } else { buffer = null; } } ~mystring(){ if(buffer){ delete buffer; } } int getlength(){ return strlen(buffer); } const char* getstring() { return buffer; } }; void usemystring(mystring const& input) { cout << "string buffer in mystring " << input.getlength() << " characters long." << endl; cout << "buffer contains: " << input.getstring() << endl; } int main(){ mystring sayhello("hello string class"); usemystring(sayhello); return 0; }
http://i.stack.imgur.com/pl4nz.jpg
two objects different char* buffer created. however, unable delete buffer. if comment out
if (buffer != null) delete buffer;
the program run through. why happen?
if allocate memory buffer = new char[length]
should free memory delete[] buffer;
but there other problems in code. why don't want use std::string
? more efficient...
i can't compile code either (i don't use windows) have issues strcpy_s
, strlen
, there issues type conversion.
Comments
Post a Comment