0

Consider the following code:

file_fd = open(device, O_RDWR);

if (file_fd < 0) {
    perror("open");
    return -1;
}

printf("File descriptor: %d\n", file_fd);

uint32_t DskSize;

if (ioctl(file_fd, BLKGETSIZE, &DskSize) < 0) {
    perror("ioctl");
    return -1;
}

printf("File descriptor after: %d\n", file_fd);

This snippet yields this:

File descriptor: 3
File descriptor after: 0

Why does my file descriptor get reset to 0? The program writes the stuff out to stdout instead of my block device.

This should not happen. I expect my file_fd to be non-zero and retain its value.

Gala
  • 2,592
  • 3
  • 25
  • 33

1 Answers1

2

Looks like you smash your stack.

Since there are only two stack variables file_fd and DskSize and changing DskSize changes file_fd suggests that DiskSize must be unsigned long or size_t (a 64-bit value), not uint32_t.

Looking at BLKGETSIZE implementation confirms that the value type is unsigned long.

You may like to run your applications under valgrind, it reports this kind of errors.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • While `valgrind` did not detect anything, you are right. I'm passing the address of a 4 byte integer to ioctl, and ioctl expects to write 8 bytes, but I only allocated 4. – Gala Aug 11 '16 at 13:38
  • @Gala I am surprised `valgrind` does not detect it. – Maxim Egorushkin Aug 11 '16 at 14:03