c - 简单的程序段错误

标签 c pointers segmentation-fault

我是 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/

相关文章:

c++ - 简单 C++ 程序中的段错误

c - VS2010 多项目解决方案 - 控制台和表单应用程序

c++ - 通过引用传递动态变量的指针

c++ - 不使用指针遍历 C 风格的数组

c++ - 释放内存的时候一定要用IF语句吗?

c - 二维数组的段错误

c++ - 来自 C 和 C++ 目标文件的共享库

c - 输出一个指针

C 代码在 Intel Xeon E5-2650 上的性能

python - 为什么以下代码在 codechef 中给出段错误,但在其他地方却工作得绝对正确