Reputation: 668
Why this piece of code causing Heap corruption when trying to delete[] fullname variable?
#include <iostream>
#include <cstring>
#include "stdafx.h"
using namespace std;
int main() {
const int size = 255;
char* firstname = new char[size];
char* lastname = new char[size];
cin.getline(firstname, size, '\n');
cin.getline(lastname, size, '\n');
int fullnamesize = strlen(firstname) + strlen(lastname) + 2;
cout << "fullname size: " << fullnamesize;
char* fullname = new char[fullnamesize];
strcpy_s(fullname, size, firstname);
strcat_s(fullname, size, " ");
strcat_s(fullname, size, lastname);
cout << "full name: " << fullname << "\n" ;
delete[] fullname;
delete[] firstname;
delete[] lastname;
cout << "hello";
return 0;
}
I cannot find what wrong with this dellocation...
Upvotes: 1
Views: 771
Reputation: 2769
What's wrong with it? It actually goes wrong at strcpy_s. Because strcpy_s overwrites the target buffer first (to the size specified in the function call). See https://msdn.microsoft.com/en-us/library/td1esda9.aspx -
The debug versions of these functions first fill the buffer with 0xFE. To disable this behavior, use _CrtSetDebugFillThreshold.
(That is quite subtle I admit!)
And you have the wrong size for the target buffer so your memory is overwritten as you've allocated only just enough memory for the fullname, but the size parameters you are passing are larger.
Why does it crash at delete[] rather than strncpy?
There's nothing wrong with the deallocation at delete[]. The problem has occurred before you get there.
The program has no idea that you've passed the wrong size in. But the strcpy function overwrites a memory management structure in the heap. This doesn't cause any problems until the delete[] call. Delete tries to use the information and discovers it's corrupt. Then you get a crash.
In a big program this type of problem is a complete nightmare.
What's the right approach?
Using the safe string functions is a great idea, but you'll need to read the manual for them carefully to ensure that you get the right result. And be much more careful about the size you are passing to them.
*PS. The old strcpy and char * approach is important to understand, but in the long run, for robust code, investigate std::string*
Upvotes: 4