开发者

strange read buffer

开发者 https://www.devze.com 2023-03-21 11:35 出处:网络
here i meet a strange problem about c read funct开发者_StackOverflow中文版ion in linux. #include <stdio.h>

here i meet a strange problem about c read funct开发者_StackOverflow中文版ion in linux.

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

int main(int argc, char** argv){
    int fd=open("a.c",O_RDONLY);
    if(fd==-1){
      fprintf(stderr,"%s\n",strerror(errno));
    }
    char buf[10];
    if(read(fd,buf,9)==-1){
      fprintf(stderr,"%s\n",strerror(errno));
    }else{
      printf("%s\n",buf);
    }
}

i think the buf should be initialize to zero, so the first 9 char read to buffer and the last one is '\0' and it like a string. but the resule is odd, below is a.c file and the result of this program, a.c

    1234567890abcd

result

    1234567893øþzôo`

seems this string is out of buffer, I can't figure out what happened, can anyone help me? thanks.


When you print a character array without ending '\0', printf will print all characters till it finds '\0' in the memory. In this case, looks like '1234567893øþzôo` is followed by '\0'. Note that printf does not know the size of 'buf' array, hence it will print even those characters present after the end of buf array.

As you have suggested it is better to either set entire buffer to 0 or add '\0' explicitly at the end (as shown in below code).

   buf[9] = '\0';


You said "i think the buf should be initialize to zero". The compiler does not do this automatically for you, so you will need to do it yourself if that is what you want:

char buf[10];
memset(buf, 0, sizeof(buf));

Before the buffer is initialized, you have no guarantees on what its contents will be.


ISTM your buffer is not zero-terminated, since you only read 9 characters. Change the last part of your code:

  if(read(fd,buf,9)==-1){
    fprintf(stderr,"%s\n",strerror(errno));
  }else{

    /* add this */ 
    buf[9] = '\0';

    printf("%s\n",buf);
  }
}

What happens if you add that?


You should initialize buf to all 0.

0

精彩评论

暂无评论...
验证码 换一张
取 消