schorsch_76
schorsch_76

Reputation: 862

read(int fd, void *buf, size_t count): prevent implicit conversion

On Linux (amd64) i read from a pipe some data of a related process. I want to ensure, that the read bytes are not changed and prevent implicit type and value conversion.

Could there happen any type conversions with "trap values" when i put the data in char or unsigned char Arrays (see the #ifdef) or should i better use a vector<> for the data read from the child? What could happen when i use a diferent platform like arm (raspi/beaglebone)? Could a conversion happen at the std::back_inserter?

        #ifdef USE_UCHAR
        using buffer_type = unsigned char;
        #else
        using buffer_type = char;
        #endif

        std::string from_child;

        std::array<buffer_type, PIPE_BUF> buffer;
        ....
        // read from it
        long bytes_read = read(fd, buffer.data(), buffer.size());
        if (bytes_read > 0) {
            std::copy_n(buffer.data(), bytes_read, std::back_inserter(from_child) );
        }
        else if (bytes_read == 0)  {
            // eof
            run = false;
        }
        else {
            perror("read from pipe:");
        }

Upvotes: 0

Views: 1751

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283793

char and unsigned char are required to treat every bit as a value bit. In addition, they are required to roundtrip, which prohibits conversions and trap values.

And std::string, for all its string-manipulation convenience functions, is at its core just a collection of characters. Inserting and iterating characters will never fail, only the string manipulation convenience functions actually assume that the character data represents a valid string.

If there were any problem, std::vector wouldn't help you, since it uses a dynamic array for holding its contents anyway.

Upvotes: 1

Related Questions