here i meet a strange problem about c read function 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.
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:
Before the buffer is initialized, you have no guarantees on what its contents will be.