ahmedrajput
ahmedrajput

Reputation: 28

Why is this code giving bad file descriptor

I am having issue with the following code. It is 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 I have found that after first iteration the value of fd is changed to a large number. I do not know how this is happening.

Upvotes: 0

Views: 2751

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

In your code

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

causes undefined behavior,as you're trying to read 20 bytes into a memory designated for sizeof(long) which is much less than what is required.

One correct way of writing this would be

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

Upvotes: 1

Related Questions