heap corruption


Works
char* lastStr=new char[strlen(this->data)+strlen(st2.data)+1];
delete[] lastStr; //delete dynamically allocated char array


Does not work. shows heap corruption
char* lastStr=new char[strlen(this->data)+strlen(st2.data)];
delete[] lastStr; //delete dynamically allocated char array

Why is it happening? and also what is best way to debug heap corruption or any runtime error?
Do you have any code between those two lines?

This code should not crash, assuming that your strings end in null characters:
1
2
char* lastStr=new char[strlen(this->data)+strlen(st2.data)];
delete[] lastStr; //delete dynamically allocated char array 

But this might:
1
2
3
4
char* lastStr=new char[strlen(this->data)+strlen(st2.data)];
strcpy(lastStr, this->data);
strcat(lastStr, st2.data);
delete[] lastStr;

Remember that you need space for the terminating null character in a C string.
you are exactly right, i have copy and concat function between this. I dont understand why it happens only it tries to free the memory not when the functions are operating. can you explain how internally this causing heap corruption?
Topic archived. No new replies allowed.