Search code examples
c++cstrncmp

strncmp not matching correctly


I have no idea how to work with strings in C:

here's a part of my server: The break never gets called, even though I supply the character '/' through telnet.

Ideally, this would buffer up the string called get by adding the string ch to it over and over again until it reaches a certain character, or, better yet, a string (but write now it is supposed to work with a character but i'd love to know how to do it with a string so I can design a protocol that uses CR+LF as the seperator).

   char ch;
    int index = 0;
    char get[1024];
    const char str[] = "/";

    if ( read( client, &ch, 1 ) < 0 )
    {
        perror( "read" );

        get[index] = ch;
        index++;

        int compareResult = strncmp(str, &ch, 5);

        if(compareResult == 0){
            index = 0;
            close( client );
            printf( "server responded, connection closed" );
            break;
        }
    }

    //if ( write( client, &ch, 1 ) < 0 ) { perror( "write" ); break; }

    printf( "got stuff" );

why does it not reach the

printf( "server responded, connection closed" );

line?

full code for server: http://pastebin.com/j5tX3TEx


Solution

  • This:

    int compareResult = strncmp(str, &ch, 5);
    

    invokes undefined behavior. You're passing &ch, the address of a single char to a function expecting a string pointer. So, it will look at at most 5 characters starting from the address of &ch, which of course is only one character of data.

    Your entire read logic is very strange, it should do larger reads and not one character at a time.