I have a class as follows
struct CliHandler {
CliHandler(int argc, char** argv);
~CliHandler();
int doWork();
int argc_;
char** argv_;
private:
CliHandler(const CliHandler&){}
CliHandler& operator=(const CliHandler&){}
};
//Constructor
CliHandler::CliHandler(int argc,
char** argv) {
//set command line parameters
argc_ = argc;
argv_ = (char**) malloc(argc_ * sizeof(char*));
for(int i=0; i<argc_; ++i)
{
std::cout<<sizeof(argv[i]);
argv_[i] = (char*) malloc(strlen(argv[i]) *
sizeof(char));
StrCpy(argv_[i], argv[i]);
} }
// destructor
CliHandler::~CliHandler() {
for(int i=0; i<argc_; ++i)
free(argv_[i]);
free(argv_); }
While I debug, I get an error " Heap corruption detected. CRT detected that application wrote to memory after end of heap buffer. " My question id "Where exactly am i making a mistake ? How do I fix it". I am using visual stdio 2008.
Edit:I did something like this to add 1
argv_[i] = (char*) malloc(strlen(argv[i] + 1) * sizeof(char));
Which is terrible as it increments the pointer argv[i] by one. My co-worker pointed out that subtle issue. It should be
argv_[i] = (char*) malloc( (strlen(argv[i]) + 1) * sizeof(char));