0

我正在编写一个使用异步类型套接字的简单客户端-服务器应用程序。但是,当我从客户端发送消息时,我收到缓冲区溢出异常。客户端代码:

#include "stdafx.h"
#include <conio.h> 
#include <winsock.h>
#include <process.h>
#include <stdlib.h>
#include <Windows.h>

#pragma comment(lib, "wsock32.lib")

#define CS_ERROR 1
#define CS_OK 0

char send_buf[1000];
char recv_buf[1000];

void MyFunction(void * Arg)
{   
    while(1)
    {         
        int Socket=(*(int *)Arg);
        send(Socket, send_buf,1000,0);  
        int n = recv(Socket,recv_buf,1000,0);
        recv_buf[n]=0;
        printf(" Answer from Server: %s",&recv_buf[0]);
        printf("\n");
    }
    _endthread();
}

int _tmain(int argc, _TCHAR* argv[])
{
    WORD version;
    WSADATA wsaData;
    int result;
    version = MAKEWORD(2,2);
    WSAStartup(version,(LPWSADATA)&wsaData);

    LPHOSTENT hostEntry;
    hostEntry = gethostbyname("127.0.0.1");
    if(!hostEntry)
    {
        printf ("%s", "  >>> ERROR  (hostEntry NULL)\n");
        WSACleanup();
        return CS_ERROR;
    }

    SOCKET theSocket = socket(AF_INET, SOCK_STREAM, 0);
    if(theSocket == SOCKET_ERROR)
    {
        printf ("%s", "  ERROR  (can't create socket)\n");
        return CS_ERROR;
    }
    else
    {
        printf ("%s", "  >>> Creating socket \n");
    }

    sockaddr_in serverInfo;
    serverInfo.sin_family = AF_INET;
    serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
    serverInfo.sin_port = htons(8888);

    result=connect(theSocket,(LPSOCKADDR)&serverInfo,
    sizeof(serverInfo));
    if(result==SOCKET_ERROR)
    {
        printf ("%s", "  ERROR (can't connect to Server)\n");
        return CS_ERROR;
    }
    else
    {
        printf ("%s", "  >>> Connecting to Server\n");
    }
    printf("Write a message: ");
    scanf_s("%s", send_buf, sizeof(send_buf));
    _beginthread(MyFunction,0,(void *)&theSocket);
    char a[100];
    scanf_s("%s", a, sizeof(a));
    return CS_OK;
}

我想这与以非法方式访问 send_buf\recv_buf 有关,但我不知道是什么。有小费吗?

4

1 回答 1

0

你打电话不scanf_s正确。scanf_s字符串输入需要两个参数——一个是指向字符串的指针,另一个是字符串的最大长度。

所以你应该这样称呼它:

scanf_s("%s", send_buf, sizeof(send_buf));
于 2014-04-28T14:37:07.060 回答