stackOverFlew
stackOverFlew

Reputation: 1489

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

Upvotes: 0

Views: 567

Answers (5)

unwind
unwind

Reputation: 399949

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.

Upvotes: 3

Jack
Jack

Reputation: 133609

read( client, &ch, 1 ) < 0

why < 0? Everything seems to be done there in your code while read returns the number of bytes read.

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25715

You do this instead:

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

This is also faster than using a function(such as strncmp)

Upvotes: 0

shazin
shazin

Reputation: 21893

Try this and see. Seems like you are comparing an array of char (str) to a char (ch)

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

Upvotes: 0

AndersK
AndersK

Reputation: 36102

The line

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

is not correct

ch is one character but you compare 5 characters. the second argument must be a string and not a char.

if it is a typo and you meant get then you need to \0 terminate the string after you received the last character in order to use get as argument. alternatively use memcmp to compare bytes regardless whether they are strings or not.

Upvotes: 2

Related Questions