c - 从命令行读取参数时出现段错误

标签 c segmentation-fault

我正在尝试在 c 中实现重复的 cat 函数。我遇到段错误,但无法找到原因。

 #include <stdio.h>
    #include <stdlib.h>




int main(int argc,char *argv[])
{
    char* s;        /* input string */

    int c;

    if(argc==1){


        while (gets(s)){
            puts(s);
        }
    }

    else{

    FILE *file = fopen( "./argv[1]", "r" );
    while((c=fgetc(file))!=EOF){
        fputc(c,stdout);

    }

    fclose(file);   

    }


    return 0;
}

最佳答案

您正在将字符读入 s不分配内存:

    while (gets(s)){
        puts(s);
    }

首先使用 malloc 分配一些内存(稍后您必须free):

    char *s = malloc(some_buffer_size);

或修复它:

    char s[some_buffer_size];

小心 gets顺便说一句,因为无法限制输入的字符数,这可能导致缓冲区溢出。使用fgets(buf, sizeof(buf), stdin)相反。

第二个错误已被别人指出,不能调用fopen像这样,用这个代替,或者使用 H2CO3 的解决方案:

 FILE *file = fopen( argv[1], "r" );

关于c - 从命令行读取参数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16030176/

相关文章:

c - 代码编译过程中出现错误

c++ - 为什么这个程序会出现段错误?

c - 将 (void*) 转换为 (int*) 时出现段错误

c++ - 未找到符号又名 undefined symbol

C 是否有允许动态函数调用的解决方法?

c++ - 提交时的 SIGSEGV

c - 使用 strlen 时出现段错误

c++ - Lambda machine-dependent segmentation-fault(可能是编译器错误?)

c++ - 什么是 NULL 值

c - 赋值运算符的重新定义