read() return extra characters from file

前端 未结 2 603
醉话见心
醉话见心 2021-01-25 06:59

I am trying to read text from file to print.. While trying if I give the char buffer size it returns some extra character ..

#include 
#include &         


        
2条回答
  •  一整个雨季
    2021-01-25 07:38

    This happens because, read() does not null-terminate the output. You need to null-terminate the destination buffer before using it as a string.

    Basically passing a non-null terminated char array to printf() as the argument to %s creates undefined behavior as there can be out of bound memory access.

    One way of achieving this is to 0-initialize the destination. That way, it will be considered null-terminated after the valid values read and stored by read(). Something like

      char cbuffer[100] = {0};
    

    can help.

    That said, change

     printf("%s",&cbuffer);
    

    to

    printf("%s",cbuffer);
    

    as %s expects a pointer to a null-terminated array of chars. When you pass the array name to a function, it decays to the pointer to the first element, so you should be ok.

提交回复
热议问题