0
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);
    }
}

在我得到的控制台中

hello world
hello world
hello stackoverflow
 stackoverflow
abcd
efgh
efgh

为什么这个程序没有完全按照它写的那样回显?

4

2 回答 2

5

memset(word, 0, 255);导致未定义的行为。您正在访问超出范围的 word 索引。另请注意,当您strlen在 word 上使用时,您应该始终零终止,因为 read 不会这样做。

于 2013-03-18T16:04:20.737 回答
1

你在循环count = read(in, word, 5);结束时调用了。while那 5 个字节被丢弃。这就是"hello"in"hello stackoverflow""abcd\n"in"abcd\nefgh"被删除的原因。

于 2013-03-18T16:07:16.873 回答