未定义的行为还是定义的行为?
Undefined behavior or defined behavior?
我正在尝试这样做:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_SIZE 50
int main()
{
char *s = malloc(sizeof(char)*MAX_SIZE);
do{
int r = read(STDIN_FILENO, s, MAX_SIZE);
if(r==-1) printf("error ");
else{
write(STDERR_FILENO, s, MAX_SIZE);
}
while(getchar()!='\n');
} while(strcmp(s,"end\n")!=0);
free(s);
return 0;
}
我的问题是:在这种情况下,fflush(stdin) 是未定义的行为吗?
当我在互联网上搜索时,我读到在某种情况下 fflush(stdin) 是一种定义的行为:
按照标准 C 将输入流传递给 fflush 是未定义的行为......
STDIN 是一个输入流(缓冲)
我认为未定义的行为是标准 C 没有指定在特定情况下哪些行为必须具有特定功能。
所以这是遵循标准 C 的未定义行为吗?
那么在这种情况下是未定义的行为吗?
C标准中对fflush
的描述似乎很清楚:
If stream points to an output stream or an update stream in which the most recent operation was not input, [...]; otherwise, the behavior is
undefined.
将输入流传递给 fflush
是未定义的行为。
我正在尝试这样做:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_SIZE 50
int main()
{
char *s = malloc(sizeof(char)*MAX_SIZE);
do{
int r = read(STDIN_FILENO, s, MAX_SIZE);
if(r==-1) printf("error ");
else{
write(STDERR_FILENO, s, MAX_SIZE);
}
while(getchar()!='\n');
} while(strcmp(s,"end\n")!=0);
free(s);
return 0;
}
我的问题是:在这种情况下,fflush(stdin) 是未定义的行为吗? 当我在互联网上搜索时,我读到在某种情况下 fflush(stdin) 是一种定义的行为: 按照标准 C 将输入流传递给 fflush 是未定义的行为...... STDIN 是一个输入流(缓冲) 我认为未定义的行为是标准 C 没有指定在特定情况下哪些行为必须具有特定功能。
所以这是遵循标准 C 的未定义行为吗?
那么在这种情况下是未定义的行为吗?
C标准中对fflush
的描述似乎很清楚:
If stream points to an output stream or an update stream in which the most recent operation was not input, [...]; otherwise, the behavior is undefined.
将输入流传递给 fflush
是未定义的行为。