我是 C 新手,我一直在尝试找出指针。
该程序与 -i 配合使用,但在几行后会出现段错误,而 -f 会立即出现段错误。
#include <stdio.h>
#include <string.h>
void search_and_print ( char pattern[], FILE* search_file );
int main ( int argc, char *argv[] ) {
const char TOO_MANY_VARIABLES[] = "Too many arguments from the command line!";
const char NOT_ENOUGH_VARIABLES[] = "\nUSAGE: a.out [-i] [-f filename] (Search Pattern)\n";
if (argc < 2) { printf(NOT_ENOUGH_VARIABLES); return(1);}
// If input
if (strcmp(argv[1],"-i") == 0) {
char *pattern = argv[2];
search_and_print(pattern, stdin);
}
// If file
if (strcmp(argv[1],"-f") == 0) {
char *pattern = argv[3];
// Check if file exists
// Open file
FILE *file = fopen( argv[2], "r" );
search_and_print(pattern, file);
fclose( file );
}
}
void search_and_print ( char pattern[], FILE* search_file ) {
// Read through file
const int MAX_CHARACTERS_PER_LINE = 1000;
char* line[MAX_CHARACTERS_PER_LINE];
while ( fgets(*line, MAX_CHARACTERS_PER_LINE, search_file) != NULL )
if ( strstr(*line, pattern) != NULL )
printf(*line);
}
最佳答案
这里有很多错误。
char* line[MAX_CHARACTERS_PER_LINE];
定义了一个包含 1000 个指针的数组,而不是字符。 fgets(*line, ...
将第一个未初始化的指针传递给 fgets
,很可能会导致 segvio。
printf(*line);
printf 的第一个参数是格式。永远不要将用户输入作为格式传递,因为这会在您的程序中打开一个巨大的安全漏洞......请参阅 http://en.wikipedia.org/wiki/Uncontrolled_format_string
您应该使用fputs(line)
或printf("%s", line)
(一旦修复了line的声明)。
int main
您不返回值(错误情况除外)...这会导致未定义的行为。
FILE *file = fopen( argv[2], "r" );
您应该检查这是否成功。如果文件无法打开(例如,它不存在),则将其传递给 fgets 会导致未定义的行为。
if (argc < 2) { printf(NOT_ENOUGH_VARIABLES); return(1);}
此测试不足以满足您的 -f 情况。
关于c - 简单的程序段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12575326/