I keep getting a debug assertion failed error and I can’t figure out why. I get the error when this code is ran:
private: System::Void txtMessage_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
if(e->KeyCode == Keys::Enter && txtMessage->Text != ""){
char* MESSAGE = new char[txtMessage->Text->Length];
ZeroMemory(MESSAGE, sizeof(MESSAGE));
string strMESSAGE = "";
MarshalString(txtMessage->Text, strMESSAGE);
memcpy(MESSAGE, strMESSAGE.c_str(), sizeof(strMESSAGE));
if (send(sConnect, MESSAGE, 256, NULL) != SOCKET_ERROR){
txtMessage->Clear();
}
}
}
Sometimes the error doesn’t occur until after I use that code multiple times and sometimes I get it the first time I use it. I really don’t know why I am getting this and, I can’t figure out how to fix it. So if anyone can help I would appreciate it.
The error I keep getting during that code is:

This is incorrect:
as it will only zeroise
sizeof(char*)bytes instead of intendedLength.The allocation for
MESSAGEis also based ontxtMessagebut is written to fromstrMessage. It may be the case that the lengths of these string objects are not equal, possibly resulting in allocating insufficient memory.The use of
memcpy()is also incorrect:as
sizeof(strMESSAGE)is not the number of characters instrMESSAGE. Uselength()instead.The call to
send()will also be attempting to access256characters fromMESSAGEwhich may be greater than that allocated forMESSAGEresulting accessing memory it should not.I am unsure why the call
send()is not simply:avoiding any dynamic memory allocation or copying.
Just to note I am unfamiliar with
MarshalString()so cannot comment on its use.