简体   繁体   中英

I get a "Debug assertion failed" error after entering the username in my TCP_Client program

I am currently a student at Automatics and Applied Informatics. I have a project from Computer Networking, in which I need to make a chat application with the help of threads. Since now I made the receiving part of the connection for the server and made the client, but I get a debug assertion failed error when I run the program. Until now I only have the user connecting part. I really need some help with this because I am stuck.

tcp_server.cpp

#include "winsock2.h"
#include "ClientThread.h"
#include <stdio.h>
#include <string.h>
#include <vector>
#include "ws2tcpip.h"
#pragma comment(lib,"ws2_32.lib")

const unsigned int SysThread::INFINIT_WAIT = UINT_MAX;

void main()
{
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("Error at WSAStartup()\n");
        return;
    }

    // Socket for listening for incoming requests
    SOCKET ListenSocket;
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ListenSocket == INVALID_SOCKET) {
        printf("Error at the listening socket, error code: %d\n", WSAGetLastError);
        WSACleanup();
        return;
    }

    int Port = 1300;
    char IP[10] = "127.0.0.1";
    sockaddr_in ServerAddress;
    int ServerLen = sizeof(ServerAddress);

    ServerAddress.sin_family = AF_INET;
    ServerAddress.sin_port = htons(Port);
    inet_pton(AF_INET, IP, &ServerAddress.sin_addr);

    if (bind(ListenSocket, (SOCKADDR*)&ServerAddress, sizeof(ServerAddress)) == SOCKET_ERROR) {
        printf("bind() failed.\n");
        closesocket(ListenSocket);
        WSACleanup();
        return;
    }

    if (listen(ListenSocket, 1) == SOCKET_ERROR) {
        printf("Error listening on socket.\n");
        WSACleanup();
        return;
    }

    std::vector <char*> username;
    int RecUserLen = 100;
    char RecUser[100];
    int ReceiveTheUsername;

    // Socket for accepting incoming requests
    SOCKET AcceptSocket;
    printf("Waiting for client to connect...\n");

    while (AcceptSocket = accept(ListenSocket, NULL, NULL)) {
        printf("Succesful connection.\n");
        int UserNum = 1;
        ReceiveTheUsername = recv(AcceptSocket, RecUser, RecUserLen-1, 0);
        username[UserNum] = RecUser;
        printf("Username: %s", username[UserNum]);
    }
}

tcp_client.cpp

#include <iostream>
#include <stdio.h>
#include <string.h>
#include "winsock2.h"
#include "ws2tcpip.h"
#pragma comment(lib, "ws2_32.lib")
void main()
{
    int iResult;
    //----------------------
    WSADATA wsaData;
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR)
        printf("Hiba a WSAStartup() –nál\n");
    //----------------------

    SOCKET ClientSocket;
    ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (ClientSocket == INVALID_SOCKET)
    {
        printf("Error at initializing the socket, error code: %ld\n",
            WSAGetLastError());
        WSACleanup();
        return;
    }
    //---------------------
    int Port = 1300;
    char IP[10] = "127.0.0.1";
    sockaddr_in ServerAddr;
    int AddrLen = sizeof(ServerAddr);

    ServerAddr.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", &ServerAddr.sin_addr);
    ServerAddr.sin_port = htons(Port);
    //----------------------
   
    if (connect(ClientSocket, (SOCKADDR*)&ServerAddr, AddrLen) == SOCKET_ERROR)
    {
        printf("Connect error, error code: %ld\n",
            WSAGetLastError());
        WSACleanup();
        return;
    }
    else {
        printf("Succesful connection.\n");
    }
    //----------------------

    char UserName[100];
    printf("Enter the username: ");
    fgets(UserName, 100, stdin);

    int SendUsername;
    SendUsername = send(ClientSocket, Felhasznalonev, sizeof(Felhasznalonev),0);
    if (SendUsername == SOCKET_ERROR) {
        printf("Error at sending the username.\n");
        closesocket(ClientSocket);
        WSACleanup();
        return;
    }

    closesocket(ClientSocket);
    WSACleanup();
    return;
}

Well there's a clear problem here

std::vector <char*> username;
...
int UserNum = 1;
...
username[UserNum] = RecUser;

username is a zero sized vector, so username[UserNum] is an out of bounds vector access.

Not really sure why you are using a vector at all, it's not adding anything to the code as it currently is. But if you do need to use one then make sure that it is big enough.

The reason for the debug assertion failed error is as John said, you did not set the size of vector <char*> username , so you cannot directly set the value in the vector through assignment.

But the reason why you output garbled characters is that the bytes you read exceed the number of bytes actually returned.

According to the document :

Return value If no error occurs, recv returns the number of bytes received and the buffer pointed to by the buf parameter will contain this data received. If the connection has been gracefully closed, the return value is zero.

Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling

So the return value of the recv function (in the code is ReceiveTheUsername ) is actually the number of bytes actually read, not RecUserLen-1 , so you can use ReceiveTheUsername to determine the validity of the returned string length.

You only need to initialize the string to be empty like the following code, you can prevent garbled characters.(Of course, you can also manually add '\0' according to the number of characters returned, or intercept the corresponding string according to the character length.)

char RecUser[100] = "";
while (AcceptSocket = accept(ListenSocket, NULL, NULL)) {
    printf("Succesful connection.\n");
    ReceiveTheUsername = recv(AcceptSocket, RecUser, RecUserLen - 1, 0);
    username.push_back(RecUser);
    printf("Username: %s", username.back());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM