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

时间:2014-02-25 23:44:59

标签: c++ udp

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

在这两种情况下,我只在服务器端收到一次数据块。通过调试我的服务器端,我观察到当我的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;
        }

    }

1 个答案:

答案 0 :(得分:2)

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

&m_vector[0]

&*m_vector.begin()

&m_vector.front()

或者,在C ++ 11中:

m_vector.data()

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