c - Why is this code giving bad file descriptor -


i having issue following code. giving me bad file descriptor error.

#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <limits.h> int main() {         int fd = open("/tmp/test", o_rdonly);         long len = 20;         long word;         ssize_t ret;         if(fd == -1)         {                 perror("open");                 return 1;         }         if(len > ssize_max)         {                 len = ssize_max;         }         ret = read(fd, &word, len);         while(len != 0 && ret != 0)         {                 if(ret == -1)                 {                         if(errno == eintr)                         {                                 continue;                         }                         perror("read");                         break;                 }                 len -= ret;                 word += ret;                 ret = read(fd, &word, len);         }         close(fd); } 

upon debugging have found after first iteration value of fd changed large number. not know how happening.

in code

 ret = read(fd, &word, len); 

causes undefined behavior,as you're trying read 20 bytes memory designated sizeof(long) less required.

one correct way of writing be

ret = read(fd, &word, sizeof(word)); 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -