# V1095. Usage of potentially invalid handle. The value should be non-negative.

The analyzer has detected that an invalid descriptor with a negative value is passed to the called function. This diagnostic is used only on POSIX-compatible platforms, because descriptors are pointers in Windows, and V575 diagnostics is used for them.

Here's a synthetic code example:

    void Process()
    {
      int fd = open("path/to/file", O_WRONLY | O_CREAT | O_TRUNC);

      char buf[32];
      size_t n = read(fd, buf, sizeof(buf)); // <=
      // ....
    }

A programmer forgot to check the result of the 'open' function. If the file cannot be opened, the 'open' function will return the -1 value, and this incorrect descriptor's value will be passed to the 'read' function.

Fixed code:

    void Process()
    {
      int fd = open("path/to/file", O_WRONLY | O_CREAT | O_TRUNC);
      if (fd < 0)
      {
        return;
      }

      char buf[32];
      size_t n = read(fd, buf, sizeof(buf));
      // ....
    }

Here's another example:

    static intoss_setformat(ddb_waveformat_t *fmt)
    {
      // ....
      if (fd)
      {
        close (fd);
        fd = 0;
      }
      fd = open (oss_device, O_WRONLY);
      // ....
    }

An incorrect handle may be passed to the 'close' function due to a poor check. In this case, a descriptor with the value of 0 can also be valid and should be released. Here we close the descriptor if the value of 'fd' is not zero. Such an error can occur, for example, after code refactoring or when the programmer is unaware that the wrong descriptor has the '-1' value, not the '0' value.

Let's fix the code fragment:

    static intoss_setformat(ddb_waveformat_t *fmt)
    {
      // ....
      if (fd >= 0)
      {
        close (fd);
        fd = -1;
      }
      fd = open (oss_device, O_WRONLY);
      // ....
    }

This diagnostic is classified as:

CWE-775