Reading from the socket and then dividing the input string is behaving not in a normal way in C





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am reading a message from the socket using this tcp_read function:



    ssize_t tcp_read(int fd, void *buf, size_t count)
{
size_t nread = 0;

while (count > 0) {
int r = read(fd, buf, count);
if (r < 0 && errno == EINTR)
continue;
if (r < 0)
return r;
if (r == 0)
return nread;
buf = (unsigned char *) buf + r;
count -= r;
nread += r;
}

return nread;
}


In the server.c file I am creating a guessing the word game, I am reading the message from the user using this tcp_read function which is close to the real read().



The user will input something like: "L: somewordrn" and I am reading this in the following way:



   char read[strlen(token2)+5];
char *token2 = "someword"
int n = tcp_read(cfd, read, strlen(token2)+5);
read[n] = '';

char *s;
size_t len = strlen(read);
s = malloc(len);
strcpy(s, read+3); //to cut 'R: '
s[len - 4] = 0;
tcp_write(cfd, s, strlen(s));

if(strcmp(token2, read) == 0)
{
tcp_write(cfd, beg_o, strlen(beg_o));
}else
{
tcp_write(cfd, beg_f, strlen(beg_f));
}


token2 is the word that the user is supposed to guess. and beg_o and beg_f are just some printing of 'Congratulation' and 'You failed'.



I did the strlen(token2) + 5, since the token2 is the word that the user should guess + 5 characters for 'R' ':' ' ' 'r' 'n', since those 5 characters are always the same every user inputs like this, only someword is what is dynamic.



In the first iteration its working, but then when the function is called again it is not working anymore (Because the second part of the code is in a big loop)



But I cannot understand why this is not working, sometimes it works sometimes it fails for example the user inputs "L: somewordrn" and the read in my function is not someword but sometimes is somew sometimes is just so. It is behaving weird.










share|improve this question

























  • Read ericlippert.com/2014/03/05/how-to-debug-small-programs for tips on debugging your code.

    – Code-Apprentice
    Nov 17 '18 at 1:34


















0















I am reading a message from the socket using this tcp_read function:



    ssize_t tcp_read(int fd, void *buf, size_t count)
{
size_t nread = 0;

while (count > 0) {
int r = read(fd, buf, count);
if (r < 0 && errno == EINTR)
continue;
if (r < 0)
return r;
if (r == 0)
return nread;
buf = (unsigned char *) buf + r;
count -= r;
nread += r;
}

return nread;
}


In the server.c file I am creating a guessing the word game, I am reading the message from the user using this tcp_read function which is close to the real read().



The user will input something like: "L: somewordrn" and I am reading this in the following way:



   char read[strlen(token2)+5];
char *token2 = "someword"
int n = tcp_read(cfd, read, strlen(token2)+5);
read[n] = '';

char *s;
size_t len = strlen(read);
s = malloc(len);
strcpy(s, read+3); //to cut 'R: '
s[len - 4] = 0;
tcp_write(cfd, s, strlen(s));

if(strcmp(token2, read) == 0)
{
tcp_write(cfd, beg_o, strlen(beg_o));
}else
{
tcp_write(cfd, beg_f, strlen(beg_f));
}


token2 is the word that the user is supposed to guess. and beg_o and beg_f are just some printing of 'Congratulation' and 'You failed'.



I did the strlen(token2) + 5, since the token2 is the word that the user should guess + 5 characters for 'R' ':' ' ' 'r' 'n', since those 5 characters are always the same every user inputs like this, only someword is what is dynamic.



In the first iteration its working, but then when the function is called again it is not working anymore (Because the second part of the code is in a big loop)



But I cannot understand why this is not working, sometimes it works sometimes it fails for example the user inputs "L: somewordrn" and the read in my function is not someword but sometimes is somew sometimes is just so. It is behaving weird.










share|improve this question

























  • Read ericlippert.com/2014/03/05/how-to-debug-small-programs for tips on debugging your code.

    – Code-Apprentice
    Nov 17 '18 at 1:34














0












0








0








I am reading a message from the socket using this tcp_read function:



    ssize_t tcp_read(int fd, void *buf, size_t count)
{
size_t nread = 0;

while (count > 0) {
int r = read(fd, buf, count);
if (r < 0 && errno == EINTR)
continue;
if (r < 0)
return r;
if (r == 0)
return nread;
buf = (unsigned char *) buf + r;
count -= r;
nread += r;
}

return nread;
}


In the server.c file I am creating a guessing the word game, I am reading the message from the user using this tcp_read function which is close to the real read().



The user will input something like: "L: somewordrn" and I am reading this in the following way:



   char read[strlen(token2)+5];
char *token2 = "someword"
int n = tcp_read(cfd, read, strlen(token2)+5);
read[n] = '';

char *s;
size_t len = strlen(read);
s = malloc(len);
strcpy(s, read+3); //to cut 'R: '
s[len - 4] = 0;
tcp_write(cfd, s, strlen(s));

if(strcmp(token2, read) == 0)
{
tcp_write(cfd, beg_o, strlen(beg_o));
}else
{
tcp_write(cfd, beg_f, strlen(beg_f));
}


token2 is the word that the user is supposed to guess. and beg_o and beg_f are just some printing of 'Congratulation' and 'You failed'.



I did the strlen(token2) + 5, since the token2 is the word that the user should guess + 5 characters for 'R' ':' ' ' 'r' 'n', since those 5 characters are always the same every user inputs like this, only someword is what is dynamic.



In the first iteration its working, but then when the function is called again it is not working anymore (Because the second part of the code is in a big loop)



But I cannot understand why this is not working, sometimes it works sometimes it fails for example the user inputs "L: somewordrn" and the read in my function is not someword but sometimes is somew sometimes is just so. It is behaving weird.










share|improve this question
















I am reading a message from the socket using this tcp_read function:



    ssize_t tcp_read(int fd, void *buf, size_t count)
{
size_t nread = 0;

while (count > 0) {
int r = read(fd, buf, count);
if (r < 0 && errno == EINTR)
continue;
if (r < 0)
return r;
if (r == 0)
return nread;
buf = (unsigned char *) buf + r;
count -= r;
nread += r;
}

return nread;
}


In the server.c file I am creating a guessing the word game, I am reading the message from the user using this tcp_read function which is close to the real read().



The user will input something like: "L: somewordrn" and I am reading this in the following way:



   char read[strlen(token2)+5];
char *token2 = "someword"
int n = tcp_read(cfd, read, strlen(token2)+5);
read[n] = '';

char *s;
size_t len = strlen(read);
s = malloc(len);
strcpy(s, read+3); //to cut 'R: '
s[len - 4] = 0;
tcp_write(cfd, s, strlen(s));

if(strcmp(token2, read) == 0)
{
tcp_write(cfd, beg_o, strlen(beg_o));
}else
{
tcp_write(cfd, beg_f, strlen(beg_f));
}


token2 is the word that the user is supposed to guess. and beg_o and beg_f are just some printing of 'Congratulation' and 'You failed'.



I did the strlen(token2) + 5, since the token2 is the word that the user should guess + 5 characters for 'R' ':' ' ' 'r' 'n', since those 5 characters are always the same every user inputs like this, only someword is what is dynamic.



In the first iteration its working, but then when the function is called again it is not working anymore (Because the second part of the code is in a big loop)



But I cannot understand why this is not working, sometimes it works sometimes it fails for example the user inputs "L: somewordrn" and the read in my function is not someword but sometimes is somew sometimes is just so. It is behaving weird.







c






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 '18 at 2:05







Dan

















asked Nov 17 '18 at 1:15









DanDan

695




695













  • Read ericlippert.com/2014/03/05/how-to-debug-small-programs for tips on debugging your code.

    – Code-Apprentice
    Nov 17 '18 at 1:34



















  • Read ericlippert.com/2014/03/05/how-to-debug-small-programs for tips on debugging your code.

    – Code-Apprentice
    Nov 17 '18 at 1:34

















Read ericlippert.com/2014/03/05/how-to-debug-small-programs for tips on debugging your code.

– Code-Apprentice
Nov 17 '18 at 1:34





Read ericlippert.com/2014/03/05/how-to-debug-small-programs for tips on debugging your code.

– Code-Apprentice
Nov 17 '18 at 1:34












2 Answers
2






active

oldest

votes


















0














I'm surprised that compiles, just looking at it. The dynamic array dims are an extension, which you should probably avoid -- just do char read[1024] or something. (Really you should use a #define for that.) But in any case, token2 is not even defined on the first line, so I don't see how the dynamic array dim can be evaluated.



Once you get over that, use a debugger. Step through line by line examining variables until you see where it's gone wrong.






share|improve this answer
























  • I have a sentence as input which I tokenize using strtok() and then I pick one of the tokens randomly and save the string in token2, so token2 is just a 'char* token2;*. But for the sake of keeping it short in StackOverflow I only posted the part which I am having the problem with. The code which you see in the second part is a part of a way more bigger function!

    – Dan
    Nov 17 '18 at 1:32













  • If you can post a compilable sample folks may be more able to help. Anyway, first thing I'd do in your situation is print buf and the return value right after calling tcp_read(). If it's always OK there, then the problem is in your main code; if it's already wrong, then your problem is in tcp_read. And so on. Divide and conquer. (Also, if I were you, I'd make sure buf is always null-terminated on return from tcp_read()).

    – GaryO
    Nov 17 '18 at 15:20











  • tcp_read() is always returning the correct input which the user is inserting, I checked it. In the first time the input like "K: somewordrn" the s = "someword" which is correct, but when I call the function for the second time for another input like "K: someotherword" the s becomes s = ": someotherwor". (token2 is being updatet and I also check it every time it is coorect, also the input is correct, so I am only suspecting on the char*s but I cannot see any errors there)

    – Dan
    Nov 17 '18 at 19:05













  • OK, so step through in a debugger. Is n always correct? Does len==n always? (In fact you shouldn't have to recompute the strlen). What is s after the strcpy? After chopping it with the null? There's not that many places it could be going wrong. (You can debug the whole thing with printfs too, just print everything, but it'll be easier to find the bug with a debugger.) You'll get it!

    – GaryO
    Nov 18 '18 at 1:37





















0














Don't return when r == 0. Wait until you reach count and return only then.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347314%2freading-from-the-socket-and-then-dividing-the-input-string-is-behaving-not-in-a%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I'm surprised that compiles, just looking at it. The dynamic array dims are an extension, which you should probably avoid -- just do char read[1024] or something. (Really you should use a #define for that.) But in any case, token2 is not even defined on the first line, so I don't see how the dynamic array dim can be evaluated.



    Once you get over that, use a debugger. Step through line by line examining variables until you see where it's gone wrong.






    share|improve this answer
























    • I have a sentence as input which I tokenize using strtok() and then I pick one of the tokens randomly and save the string in token2, so token2 is just a 'char* token2;*. But for the sake of keeping it short in StackOverflow I only posted the part which I am having the problem with. The code which you see in the second part is a part of a way more bigger function!

      – Dan
      Nov 17 '18 at 1:32













    • If you can post a compilable sample folks may be more able to help. Anyway, first thing I'd do in your situation is print buf and the return value right after calling tcp_read(). If it's always OK there, then the problem is in your main code; if it's already wrong, then your problem is in tcp_read. And so on. Divide and conquer. (Also, if I were you, I'd make sure buf is always null-terminated on return from tcp_read()).

      – GaryO
      Nov 17 '18 at 15:20











    • tcp_read() is always returning the correct input which the user is inserting, I checked it. In the first time the input like "K: somewordrn" the s = "someword" which is correct, but when I call the function for the second time for another input like "K: someotherword" the s becomes s = ": someotherwor". (token2 is being updatet and I also check it every time it is coorect, also the input is correct, so I am only suspecting on the char*s but I cannot see any errors there)

      – Dan
      Nov 17 '18 at 19:05













    • OK, so step through in a debugger. Is n always correct? Does len==n always? (In fact you shouldn't have to recompute the strlen). What is s after the strcpy? After chopping it with the null? There's not that many places it could be going wrong. (You can debug the whole thing with printfs too, just print everything, but it'll be easier to find the bug with a debugger.) You'll get it!

      – GaryO
      Nov 18 '18 at 1:37


















    0














    I'm surprised that compiles, just looking at it. The dynamic array dims are an extension, which you should probably avoid -- just do char read[1024] or something. (Really you should use a #define for that.) But in any case, token2 is not even defined on the first line, so I don't see how the dynamic array dim can be evaluated.



    Once you get over that, use a debugger. Step through line by line examining variables until you see where it's gone wrong.






    share|improve this answer
























    • I have a sentence as input which I tokenize using strtok() and then I pick one of the tokens randomly and save the string in token2, so token2 is just a 'char* token2;*. But for the sake of keeping it short in StackOverflow I only posted the part which I am having the problem with. The code which you see in the second part is a part of a way more bigger function!

      – Dan
      Nov 17 '18 at 1:32













    • If you can post a compilable sample folks may be more able to help. Anyway, first thing I'd do in your situation is print buf and the return value right after calling tcp_read(). If it's always OK there, then the problem is in your main code; if it's already wrong, then your problem is in tcp_read. And so on. Divide and conquer. (Also, if I were you, I'd make sure buf is always null-terminated on return from tcp_read()).

      – GaryO
      Nov 17 '18 at 15:20











    • tcp_read() is always returning the correct input which the user is inserting, I checked it. In the first time the input like "K: somewordrn" the s = "someword" which is correct, but when I call the function for the second time for another input like "K: someotherword" the s becomes s = ": someotherwor". (token2 is being updatet and I also check it every time it is coorect, also the input is correct, so I am only suspecting on the char*s but I cannot see any errors there)

      – Dan
      Nov 17 '18 at 19:05













    • OK, so step through in a debugger. Is n always correct? Does len==n always? (In fact you shouldn't have to recompute the strlen). What is s after the strcpy? After chopping it with the null? There's not that many places it could be going wrong. (You can debug the whole thing with printfs too, just print everything, but it'll be easier to find the bug with a debugger.) You'll get it!

      – GaryO
      Nov 18 '18 at 1:37
















    0












    0








    0







    I'm surprised that compiles, just looking at it. The dynamic array dims are an extension, which you should probably avoid -- just do char read[1024] or something. (Really you should use a #define for that.) But in any case, token2 is not even defined on the first line, so I don't see how the dynamic array dim can be evaluated.



    Once you get over that, use a debugger. Step through line by line examining variables until you see where it's gone wrong.






    share|improve this answer













    I'm surprised that compiles, just looking at it. The dynamic array dims are an extension, which you should probably avoid -- just do char read[1024] or something. (Really you should use a #define for that.) But in any case, token2 is not even defined on the first line, so I don't see how the dynamic array dim can be evaluated.



    Once you get over that, use a debugger. Step through line by line examining variables until you see where it's gone wrong.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 17 '18 at 1:29









    GaryOGaryO

    1,4921219




    1,4921219













    • I have a sentence as input which I tokenize using strtok() and then I pick one of the tokens randomly and save the string in token2, so token2 is just a 'char* token2;*. But for the sake of keeping it short in StackOverflow I only posted the part which I am having the problem with. The code which you see in the second part is a part of a way more bigger function!

      – Dan
      Nov 17 '18 at 1:32













    • If you can post a compilable sample folks may be more able to help. Anyway, first thing I'd do in your situation is print buf and the return value right after calling tcp_read(). If it's always OK there, then the problem is in your main code; if it's already wrong, then your problem is in tcp_read. And so on. Divide and conquer. (Also, if I were you, I'd make sure buf is always null-terminated on return from tcp_read()).

      – GaryO
      Nov 17 '18 at 15:20











    • tcp_read() is always returning the correct input which the user is inserting, I checked it. In the first time the input like "K: somewordrn" the s = "someword" which is correct, but when I call the function for the second time for another input like "K: someotherword" the s becomes s = ": someotherwor". (token2 is being updatet and I also check it every time it is coorect, also the input is correct, so I am only suspecting on the char*s but I cannot see any errors there)

      – Dan
      Nov 17 '18 at 19:05













    • OK, so step through in a debugger. Is n always correct? Does len==n always? (In fact you shouldn't have to recompute the strlen). What is s after the strcpy? After chopping it with the null? There's not that many places it could be going wrong. (You can debug the whole thing with printfs too, just print everything, but it'll be easier to find the bug with a debugger.) You'll get it!

      – GaryO
      Nov 18 '18 at 1:37





















    • I have a sentence as input which I tokenize using strtok() and then I pick one of the tokens randomly and save the string in token2, so token2 is just a 'char* token2;*. But for the sake of keeping it short in StackOverflow I only posted the part which I am having the problem with. The code which you see in the second part is a part of a way more bigger function!

      – Dan
      Nov 17 '18 at 1:32













    • If you can post a compilable sample folks may be more able to help. Anyway, first thing I'd do in your situation is print buf and the return value right after calling tcp_read(). If it's always OK there, then the problem is in your main code; if it's already wrong, then your problem is in tcp_read. And so on. Divide and conquer. (Also, if I were you, I'd make sure buf is always null-terminated on return from tcp_read()).

      – GaryO
      Nov 17 '18 at 15:20











    • tcp_read() is always returning the correct input which the user is inserting, I checked it. In the first time the input like "K: somewordrn" the s = "someword" which is correct, but when I call the function for the second time for another input like "K: someotherword" the s becomes s = ": someotherwor". (token2 is being updatet and I also check it every time it is coorect, also the input is correct, so I am only suspecting on the char*s but I cannot see any errors there)

      – Dan
      Nov 17 '18 at 19:05













    • OK, so step through in a debugger. Is n always correct? Does len==n always? (In fact you shouldn't have to recompute the strlen). What is s after the strcpy? After chopping it with the null? There's not that many places it could be going wrong. (You can debug the whole thing with printfs too, just print everything, but it'll be easier to find the bug with a debugger.) You'll get it!

      – GaryO
      Nov 18 '18 at 1:37



















    I have a sentence as input which I tokenize using strtok() and then I pick one of the tokens randomly and save the string in token2, so token2 is just a 'char* token2;*. But for the sake of keeping it short in StackOverflow I only posted the part which I am having the problem with. The code which you see in the second part is a part of a way more bigger function!

    – Dan
    Nov 17 '18 at 1:32







    I have a sentence as input which I tokenize using strtok() and then I pick one of the tokens randomly and save the string in token2, so token2 is just a 'char* token2;*. But for the sake of keeping it short in StackOverflow I only posted the part which I am having the problem with. The code which you see in the second part is a part of a way more bigger function!

    – Dan
    Nov 17 '18 at 1:32















    If you can post a compilable sample folks may be more able to help. Anyway, first thing I'd do in your situation is print buf and the return value right after calling tcp_read(). If it's always OK there, then the problem is in your main code; if it's already wrong, then your problem is in tcp_read. And so on. Divide and conquer. (Also, if I were you, I'd make sure buf is always null-terminated on return from tcp_read()).

    – GaryO
    Nov 17 '18 at 15:20





    If you can post a compilable sample folks may be more able to help. Anyway, first thing I'd do in your situation is print buf and the return value right after calling tcp_read(). If it's always OK there, then the problem is in your main code; if it's already wrong, then your problem is in tcp_read. And so on. Divide and conquer. (Also, if I were you, I'd make sure buf is always null-terminated on return from tcp_read()).

    – GaryO
    Nov 17 '18 at 15:20













    tcp_read() is always returning the correct input which the user is inserting, I checked it. In the first time the input like "K: somewordrn" the s = "someword" which is correct, but when I call the function for the second time for another input like "K: someotherword" the s becomes s = ": someotherwor". (token2 is being updatet and I also check it every time it is coorect, also the input is correct, so I am only suspecting on the char*s but I cannot see any errors there)

    – Dan
    Nov 17 '18 at 19:05







    tcp_read() is always returning the correct input which the user is inserting, I checked it. In the first time the input like "K: somewordrn" the s = "someword" which is correct, but when I call the function for the second time for another input like "K: someotherword" the s becomes s = ": someotherwor". (token2 is being updatet and I also check it every time it is coorect, also the input is correct, so I am only suspecting on the char*s but I cannot see any errors there)

    – Dan
    Nov 17 '18 at 19:05















    OK, so step through in a debugger. Is n always correct? Does len==n always? (In fact you shouldn't have to recompute the strlen). What is s after the strcpy? After chopping it with the null? There's not that many places it could be going wrong. (You can debug the whole thing with printfs too, just print everything, but it'll be easier to find the bug with a debugger.) You'll get it!

    – GaryO
    Nov 18 '18 at 1:37







    OK, so step through in a debugger. Is n always correct? Does len==n always? (In fact you shouldn't have to recompute the strlen). What is s after the strcpy? After chopping it with the null? There's not that many places it could be going wrong. (You can debug the whole thing with printfs too, just print everything, but it'll be easier to find the bug with a debugger.) You'll get it!

    – GaryO
    Nov 18 '18 at 1:37















    0














    Don't return when r == 0. Wait until you reach count and return only then.






    share|improve this answer




























      0














      Don't return when r == 0. Wait until you reach count and return only then.






      share|improve this answer


























        0












        0








        0







        Don't return when r == 0. Wait until you reach count and return only then.






        share|improve this answer













        Don't return when r == 0. Wait until you reach count and return only then.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 17 '18 at 1:32









        obeobe

        3,51531427




        3,51531427






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347314%2freading-from-the-socket-and-then-dividing-the-input-string-is-behaving-not-in-a%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python