使用scanf_s时缓冲区溢出问题

时间:2014-04-28 14:33:30

标签: c++ sockets asynchronous buffer overrun

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

#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有关,但我无法弄清楚是什么。有什么提示吗?

1 个答案:

答案 0 :(得分:0)

您没有正确调用scanf_sscanf_s需要两个参数用于字符串输入 - 一个带有指向字符串的指针,另一个带有字符串的最大长度。

所以你应该这样称呼它:

scanf_s("%s", send_buf, sizeof(send_buf));