I want to copy an object and send it over the network with winsock, but there is one problem. I destroy the stack if I copy an object to an array of chars on the heap. Here is my code:
testclass backditup; //This is an object with information
testclass restorenaarhier; //I will copy it to this object
backditup.setvalues(100,100);
restorenaarhier.setvalues(0,0);
char * dataholder = new char[sizeof(backditup)]; //This is the data holder
ZeroMemory(&dataholder,sizeof(backditup));
memcpy(&dataholder,&backditup,sizeof(backditup)); //Save it to the char[]
//Sending it over the network
//resieving the object
//Store the data on the same object
memcpy(&restorenaarhier,&dataholder,sizeof(restorenaarhier));
//deleting the data holder
ZeroMemory(&dataholder,sizeof(dataholder));
delete dataholder;
//output the code
restorenaarhier.echo();
The code will work properly, but when I compile this in debug mode I get at the end:
http://imageshack.us/photo/my-images/839/errormnr.png/
Run-Time Check Failure #2 Stack around the variable ‘dataholder’ was corrupted.
Can someone help me with this?
Your
dataholdervariable is a pointer to an array the size ofbackditup, not the array itself. Thus, when you do theZeromemoryandmemcpycalls, you should not take its address; instead, write:without the
&. Likewise, when you copy the data back, you want:And, finally, you need to make the same fix in the second
Zeromemorycall — although, since you are deleting the array immediately after that call, there really is no point in having that call at all.The size in the second
Zeromemorycall is erroneous for the same reason;sizeof(dataholder)is the size of the pointer, not the array it’s pointing to. If you don’t simply delete this call entirely, you should either usesizeof(backditup)here for consistency with the declaration, or better yet, declare a variable to hold the length of the dataholder array and use that consistently. (Or you can use the size of the data type,sizeof(testclass)— that’s probably the best option.)Finally, as Mark Wilkins noted in his answer, you need to delete arrays with
delete[], notdelete, to avoid corrupting the heap.