我想复制一个对象并通过网络使用winsock发送它,但有一个问题。如果我将一个对象复制到堆上的字符数组中,我会销毁堆栈。这里是我的代码:memcpy后栈损坏
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();
代码将正常工作,但是当我编译这在调试模式下我在最后得到:
http://imageshack.us/photo/my-images/839/errormnr.png/
运行时检查失败#2堆栈周围的变量'数据持有者'被破坏。
有人可以帮助我吗?
将'char * dataholder = new char [sizeof(backditup)];'改为'char * dataholder = new char [sizeof(backditup)]();'不需要任何'ZeroMemory'。这不是C,它是C++,所以你应该使用C++习惯用法。 – ildjarn 2012-02-02 21:58:44