Heap corruption while freeing memory

I have a class as follows

 struct CliHandler {
     CliHandler(int argc, char** argv);

     int doWork();

     int argc_; 
     char** argv_;  
     CliHandler(const CliHandler&){}
     CliHandler& operator=(const CliHandler&){} 


 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)
         argv_[i] = (char*) malloc(strlen(argv[i]) *
         StrCpy(argv_[i], argv[i]);
     } }

// destructor

 CliHandler::~CliHandler() {
     for(int i=0; i<argc_; ++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));


Change the code to:

 argv_[i] = (char*) malloc(strlen(argv[i]) + 1) ; 
 strcpy(argv_[i], argv[i]); 

It's because your StrCpy likely trashes your memory. You have to account for the terminating nul byte as well, provided your StrCpy works like the standard strcpy (which it has to in order to be useful, better just use the standard strcpy() unless you have a good reason not to).

sizeof(char) is by definition 1, so that can be omitted too.

Please use strdup() - it allocates the right amount of memory and copies characters for you.

You need to allocate one character more than the strlen of a C-string if you want to copy it. This is because strlen does not count the termination null-character.

If StrCpy is anything like strcpy, it will write one byte more than strlen() returns, to zero terminate the string.


 ? Heap corruption while freeing memory
 ? Heap corruption while freeing memory
 ? heap corruption detected after normal block(#174)
 ? Heap corruption when trimming delayed free queue
 ? Heap corruption on free(...)
 ? Heap corruption while freeing memory in a recursion function
 ? Heap Corruption double freeing memory
 ? trying to free allocated memory generate heap error
 ? Heap corruption while freeing memory
 ? Heap corruption error while trying to free a two-dimentional array