Question

Ok, so I have a client that is trying to connect to the server. I call the function below. After the function does its' work and is about to return the client program crashes. I used the debugger and I noticed a very unusual thing. After the return statement controls jumps to unknown function (as I understand). IDE (Code::Blocks) prints this before client crash:

At C:...\client.c:55

In ?? () ()

Failure finding "Stack level " Failure matching reg_output

Program received signal SIGSEGV, Segmentation fault.

Here is the code:

SOCKET InitializeClient( void )
{
    SOCKET ClientsockDesc;
    char ServerHostName [256] = {0};
    unsigned short int ServerPortNumber;
    struct sockaddr_in ServerAddress;
    struct hostent *ptrServerHostEntry = NULL;
    char Temp [10] = {0};
    const char yes = '1';
    char* Packet;

    while( 0 == strcmp(ServerHostName, "") )
    {
        printf("Input the host name: ");
        fgets(ServerHostName, sizeof(ServerHostName), stdin);
    }
    ServerHostName[strlen(ServerHostName) - 1] = '\0';

    while( 0 == strcmp(Temp, "") )
    {
        printf("Input the server port number: ");
        fgets(Temp, sizeof(Temp), stdin);
    }
    Temp[strlen(Temp) - 1] = '\0';
    ServerPortNumber = (unsigned short int)atoi(Temp);

    if( NULL ==(ptrServerHostEntry = gethostbyname(ServerHostName)) )
        return INVALID_SOCKET;

    ServerAddress.sin_family    = AF_INET;
    ServerAddress.sin_port      = htons( ServerPortNumber );
    ServerAddress.sin_addr      = *(struct in_addr *)ptrServerHostEntry->h_addr;
    memset(&(ServerAddress.sin_zero), 0, 8);
    if( INVALID_SOCKET ==(ClientsockDesc = socket(AF_INET, SOCK_STREAM, 0)) )
        return INVALID_SOCKET;
    if( SOCKET_ERROR == setsockopt(ClientsockDesc,
        SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) )
        return INVALID_SOCKET;
    if( SOCKET_ERROR == connect(ClientsockDesc, (struct sockaddr *)&ServerAddress, sizeof(struct sockaddr)) )
    {
        closesocket(ClientsockDesc);
        return INVALID_SOCKET;
    }
    printf("Successfully connected to host \'%s\' -(%s).\n",
        ServerHostName, inet_ntoa(*(struct in_addr *)ptrServerHostEntry->h_addr) );
    if( SOCKET_ERROR == ReceivePacket(&ClientsockDesc, Packet) )
    {
        closesocket(ClientsockDesc);
        return INVALID_SOCKET;
    }
    printf("%s", Packet);
    return ClientsockDesc;
}

Any help would be appreciated. I would be happy to provide any additional information.

Was it helpful?

Solution

You are passing un uninitilized variable to ReceivePacket:

char* Packet;

<skipped lines>

if( SOCKET_ERROR == ReceivePacket(&ClientsockDesc, Packet) )
{

C passes by value, which means that after the call, Packet is still uninitialized.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top