简体   繁体   中英

Why doesn't write() work properly?

int main() {
    int in = STDIN_FILENO;
    int out = STDOUT_FILENO;
    char word[100];
    int count;

    while ((count = read(in, word, 100)) != 0) {
        write(out, word, strlen(word));
        memset(word, 0, 255);
        count = read(in, word, 5);
    }
}

In the console I got

hello world
hello world
hello stackoverflow
 stackoverflow
abcd
efgh
efgh

Why isn't this program echoing back exactly as it was written?

memset(word, 0, 255); is causing undefined behavior. You are accessing index out of bounds for word. Also please note that as you are using strlen on word, you should always zero terminate as read does not do that.

You called count = read(in, word, 5); in the end of the while loop. That 5 bytes are dropped. That's why the "hello" in "hello stackoverflow" and the "abcd\\n" in "abcd\\nefgh" are dropped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM