c++ - Why this causing Heap corruption? -
why piece of code causing heap corruption when trying 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 wrong dellocation...
what's wrong it? goes wrong @ strcpy_s. because strcpy_s overwrites target buffer first (to size specified in function call). see https://msdn.microsoft.com/en-us/library/td1esda9.aspx -
the debug versions of these functions first fill buffer 0xfe. disable behavior, use _crtsetdebugfillthreshold.
(that quite subtle admit!)
and have wrong size target buffer memory overwritten you've allocated enough memory fullname, size parameters passing larger.
why crash @ delete[] rather strncpy?
there's nothing wrong deallocation @ delete[]. problem has occurred before there.
the program has no idea you've passed wrong size in. strcpy function overwrites memory management structure in heap. doesn't cause problems until delete[] call. delete tries use information , discovers it's corrupt. crash.
in big program type of problem complete nightmare.
what's right approach?
using safe string functions great idea, you'll need read manual them ensure right result. , more careful size passing them.
*ps. old strcpy , char * approach important understand, in long run, robust code, investigate std::string*
Comments
Post a Comment