I'm getting an access violation on a char array I just created using new
.
DispatchCommand(char* cmdStr)
{
// Dispatch
for(int i = 0; i < sizeof(_lpCommands); i++)
{
const int len = strlen(_lpCommands[i].szCommand);
char* cmdblip = new char[len + 1];
memcpy(&cmdblip, cmdStr, len);
cmdblip[len] = '\0'; // Access Violation
if(strcmp(cmdblip, _lpCommands[i].szCommand) == 0)
{
if(strlen(cmdStr) > strlen(_lpCommands[i].szCommand))
(*_lpCommands[i].cbCallback)(&cmdStr[strlen(_lpCommands[i].szCommand)]);
else
(*_lpCommands[i].cbCallback)("");
delete cmdblip;
return;
}
delete cmdblip;
}
// Error and return
*Out::ServerInfo<<"Command not found!"<<ENDL;
}
_lpCommands is an array of Command
structures:
struct Command
{
char* szCommand;
CommandCallback cbCallback;
};
The produced error message is:
Unhandled exception at 0x012219cf in Program.exe: 0xC0000005: Access violation writing location 0x66647366.
This was a rewrite of similar code which was using memcmp
, which ended up giving me an access violation as well without be doing a memcpy
.
What gives?
Don't pass &cmdblip
to memcpy
. You should pass a pointer to the destination buffer, not a pointer to that pointer. Pass cmdblip
instead.
Edit: I agree that in general, std::string should be used in C++. Still, the technical reason this code crashes is that memcpy
corrupts the cmdblip
pointer, making it point on a memory location that is actually made of the first 4 bytes of the copied string. Then, cmdblip[len]
results in a memory location that is not within the allocated buffer (or any other legally allocated buffer), hence the crash. So, if you want to write better code, use C++ classes. And if you want to understand why the given code crashed, consider the above.