gpt4 book ai didi

c++ - UDP套接字recvfrom中的访问冲突读取位置

转载 作者:行者123 更新时间:2023-11-28 02:55:48 25 4
gpt4 key购买 nike

我试图从客户端多次获取一个数据 block (800 字节)。之前我试图获取没有前缀长度信息的数据 block ,但后来我开始向服务器发送带有数据 block 前缀长度信息的数据 block 。

在这两种情况下,我只在服务器端收到一次数据 block 。通过调试我的服务器端,我观察到当我的 while(1) 循环尝试第二次执行时,我得到一个调试错误

First-chance exception at 0x012e2e53 in UDP_server.exe: 0xC0000005: Access violation reading location 0xbd63841d.
Unhandled exception at 0x012e2e53 in UDP_server.exe: 0xC0000005: Access violation reading location 0xbd63841d.

我自己尝试了很多东西,但仍然无法弄清楚是怎么回事。

//服务器代码

int total_bytes = 0;
int bytes_recv=0;
int count = 0;
uint32_t nlength =0;
std::vector<double> m_vector(nlength/sizeof(double));
int length_received;
while(1)
{
//code to received data length from the client
length_received = recvfrom(Socket,(char*)&nlength, 4, 0,(SOCKADDR*)&ClientAddr,&i);
m_vector.resize(nlength/sizeof(double));

//code to received data length from the client
int bytes_recv = recvfrom(Socket,(char*)&m_vector,nlength,0,(SOCKADDR*)&ClientAddr,&i);
count++;

if((bytes_recv > 0 ))
{
total_bytes = total_bytes+bytes_recv;
std::cout<<"Server: loop counter is"<<count<<std::endl;
std::cout<<"Server: Received bytes are"<<total_bytes<<std::endl;
}else
{
std::cout<<"Data Receiving has finished"<<std::endl;
break;
}

}

最佳答案

(char*)&m_vector 不正确。要正确地将 vector 转换为数组,请执行以下操作:

&m_vector[0]

&*m_vector.begin()

&m_vector.front()

或者,在 C++11 中:

m_vector.data()

在 Windows 上,您可能还需要将表达式转换为 char*,因为 Windows recvfrom采用 char* 缓冲区,而不是 void*

关于c++ - UDP套接字recvfrom中的访问冲突读取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22028718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com