【问题标题】:C - History of commands (core dumped)C - 命令历史(核心转储)
【发布时间】:2017-11-17 07:16:31
【问题描述】:

我正在尝试删除 file1 的第 20 行。该程序的其余部分是一个简单的外壳,它只能工作我无法记录用户使用的命令的历史。 当我尝试插入命令时出现的错误消息是:Segmentation fault (core dumped)

我正在执行的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

#define GetCurrentDir getcwd  //get the path of file
#define BUFFER_LEN 1024

int ch;
FILE *file1, file2;
char line[BUFFER_LEN]    

while(1){
    if(!fgets(line, BUFFER_LEN, stdin))
    {                       
        break;              
    }
    else if(line, BUFFER_LEN, SIGQUIT){
                fopen("fileOne.c","r");
            while((ch = getc(file1)) != EOF){   
                printf("%s",ch);
            } 
        } 

        if(count<20)
        {
            fputs(argv[100] ,file1);  
        }
        else{
            fclose(file1);
            file1 = fopen("fileOne.c","r"); 
            rewind(file1);        
            file2 = fopen("repicla.c","w"); 
            while((ch = getc(file1)) != EOF){              
                if((ch = getc(file1)) != "\n"){         
                    count++;            
                    if(count != 20){                
                    putc(ch, file2);            
                    }
                }   
            }   
            fclose(file1);  
            fclose(file2);  
            remove("fileOne.c");    
            rename("replica.c","fileOne.c");    
            fputs(argv[100] ,file1);   
        }
}

【问题讨论】:

  • 1) fopen("fileOne.c","r"); --> file1 = fopen("fileOne.c","r");, printf("%s",ch); --> printf("%c",ch);. BTW 这个可以编译吗?
  • 可以编译,还是报同样的错误

标签: c linux file ubuntu


【解决方案1】:

最重要的是,我无法编译你的代码!我很快就会深入研究,但我怀疑你的代码中存在重大错误,你需要一本不同的书,因为无论什么书你正在阅读(你正在阅读而不是猜测,对吗?),这对你来说不太好。你考虑过 K&R2E 吗?

我的编译器会发出错误消息,你的也会如此。您可能正在尝试执行我们无法帮助您的陈旧二进制文件。你需要让你的代码可编译。

假设问题已得到解决,您的以下代码中存在错误,您的编译器可能会警告您:

while((ch = getc(file1)) != EOF){   
    printf("%s",ch);
} 

您将int 对应于%s 格式委托传递给printf。你需要传递一个char *。如果你传递了错误的类型,你会得到未定义的行为,这很可能会导致崩溃。

在这种情况下,我认为您可能打算使用putchar(ch); 或printf("%c",ch);。

尽管如此,当你的编译器对你大喊大叫时,不要忽略它!如果你不理解错误或警告,问一个问题,而不是!

【讨论】:

    【解决方案2】:

    给定

    int ch;
    

    这一行是未定义的行为:

    printf("%s",ch);
    

    %s 是 nul 终止字符串的格式。但是ch 是一个int 值,因此printf() 代码几乎可以肯定将传递的int 值视为一个地址,并尝试将其用作以nul 结尾的起始地址字符串。

    这是强制从SIGSEGV 进行核心转储的可靠方法。

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 2014-02-26
      • 2019-07-28
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      相关资源
      最近更新 更多