Heap WinSock2应用程序遇到堆损坏

Heap WinSock2应用程序遇到堆损坏,heap,winsock,corruption,Heap,Winsock,Corruption,我觉得这是一个愚蠢的错误,但我正在制作一个echo服务器来识别数据包,并输出数据,然后重新发送回去。它对一些数据包有效,但我试图回传的一个数据包被破坏,并说有一个堆被破坏了 Vector类,目前仅用作容器: class-vec2 { 公众: vec2(){}; 浮动x,y; }; PlayerData结构: struct PlayerData { vec2位置; 国际卫生组织; 浮动旋转; 字符移动标志; 短playerID; }; 我正在尝试发送的数据包: struct ServerPac

我觉得这是一个愚蠢的错误,但我正在制作一个echo服务器来识别数据包,并输出数据,然后重新发送回去。它对一些数据包有效,但我试图回传的一个数据包被破坏,并说有一个堆被破坏了

Vector类,目前仅用作容器:

class-vec2
{
公众:
vec2(){};
浮动x,y;
};
PlayerData结构:

struct PlayerData
{
vec2位置;
国际卫生组织;
浮动旋转;
字符移动标志;
短playerID;
};
我正在尝试发送的数据包:

struct ServerPacket\u SyncGame//5
{
短包装;
PlayerData数据[8];
};
下一部分是混乱的,但我将对其进行评论,试图让它有意义

ServerPacket\u SyncGame*SP\u SG=newserverpacket\u SyncGame//创建数据包指针
for(int i=0;i<8;i++)//在数据包数组中分配八个playerdata结构
{
SP_SG->数据[i]。playerID=i;
SP_SG->数据[i]。运行状况=rand()%30;
SP_SG->data[i].moveflags='D';
SP_SG->data[i].pos.x=rand()%1000;
SP_SG->数据[i]。位置y=rand()%1000;
SP_SG->数据[i]。旋转=rand()%360;
}
SP_SG->packetID=5//分配数据包id

cout您只为
recv()
缓冲区分配了1个字节,但您正在尝试将
sizeof(ServerPacket\u SyncGame)
字节数读入缓冲区。您需要更改以下内容:

char* SP_SG_RCVBUFF = new char; //new buffer for recv
为此:

char* SP_SG_RCVBUFF = new char[sizeof(ServerPacket_SyncGame)];
for
循环相同:

for(;;)
{
    //char* buffer = new char;
    char* buffer = new char[sizeof(ServerPacket_SyncGame)];
    //char* temp = new char;
    char* temp = new char[sizeof(ServerPacket_SyncGame)];
    ...
 };
我建议您清理代码:

ServerPacket_SyncGame* SP_SG = new ServerPacket_SyncGame; //creates packet pointer
for(int i = 0; i < 8; i++) //assigns the eight playerdata structs in the packet array
{
    SP_SG->data[i].playerID = i;
    SP_SG->data[i].health = rand() % 30;
    SP_SG->data[i].moveflags = 'D';
    SP_SG->data[i].pos.x = rand() % 1000;
    SP_SG->data[i].pos.y = rand() % 1000;
    SP_SG->data[i].rotation = rand() % 360;
}
SP_SG->packetID = 5; //assigns the packet id
...
// don't forget to do error handling on this, and pay attention to the
// return value so you know if you actually sent the entire struct or not...
send(Socket, (char*)SP_SG, sizeof(ServerPacket_SyncGame), 0);
delete SP_SG;

SP_SG = new ServerPacket_SyncGame;

// don't forget to do error handling on this, and pay attention to the
// return value so you know if you actually received the entire struct or not...
recv(Socket, (char*)SP_SG, sizeof(ServerPacket_SyncGame), 0); //recv new buffer
...
delete SP_SG;

非常感谢,它现在可以工作了。还感谢您对清理我的代码的建议!我真的需要它们。
ServerPacket_SyncGame buffer;
for(;;)
{
    // don't forget to do error handling on this, and pay attention to the
    // return value so you know if you actually received the entire struct or not...
    int size = recv(Socket, &buffer, sizeof(ServerPacket_SyncGame), 0);
    if (size > 0)
    {
        // don't forget to do error handling on this, and pay attention to the
        // return value so you know if you actually sent the entire struct or not...
        send(Socket, (char*)InterpretInfo(&buffer), size, 0);
    }
 };