【问题标题】:Segmenation fault in file handling operations in C?C中文件处理操作中的分段错误?
【发布时间】:2017-11-19 21:19:31
【问题描述】:

我是 UNIX 中文件处理的新手,我无法弄清楚我在哪里以及如何遇到分段错误。是否有任何我没有分配的内存,或者它是实际打开和读取文件的问题。注意:在同一目录中有一个名为“hi.txt”的空文本文件。

read.c

#include <stdio.h>
#include <string.h>

FILE *fp;
FILE *wp;

void open(char *name)
{
    char *outname = strcat(name, ".rzip");
    fp = fopen(name, "r");
    wp = fopen(outname, "w");
}

char read()
{
    return getc(fp);
}

void write(char c)
{
    putc(c, wp);
}

void close()
{
    fclose(fp);
}

main.c

void open(char *);
char read();
void write(char);
void close();

int main()
{
    open("hi.txt");
    write('c');
    close();

    return 0;
}

【问题讨论】:

  • "hi.txt" 没有空间来组合其他字符串。例如open("hi.txt"); --> char filename[256] = "hi.txt"; open(filename);
  • 并避免使用openreadwriteclose 之类的名称。
  • @BLUEPIXY 嗯,我似乎仍然遇到了段错误。另外,我会听取您的建议并更改这些函数名称。编辑:现在已经修好了。我应该改用什么名字?
  • 例如open --> my_open.

标签: c file unix


【解决方案1】:

BLUEPIXY 的评论很到位。您在字符串常量上滥用strcat

要在 Linux 中快速调试分段错误,您应该使用操作系统提供的 core dump 工具。

很简单:

  1. 使用-g 选项编译

    $ gcc -o read main.c read.c -g

  2. 取消对核心转储文件大小的限制

    $ ulimit -c unlimited

  3. 运行程序

    $ ./read Segmentation fault (core dumped)

  4. 检查core文件是否已经生成

    $ ls -l -rw------- 1 user01 users 258048 Jun 17 10:30 core -rw-r--r-- 1 user01 users 144 Jun 17 10:23 main.c -rwxr-xr-x 1 user01 users 14960 Jun 17 10:24 read -rw-r--r-- 1 user01 users 300 Jun 17 10:23 read.c

  5. 在核心文件上运行 gdb

    $ gdb ./read ./core GNU gdb (GDB; openSUSE Leap 42.2) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ... [New LWP 24468] Core was generated by ./read. Program terminated with signal SIGSEGV, Segmentation fault. 0 0x000000000040071b in open (name=0x400834 "hi.txt") at read.c:9 9 char *outname = strcat(name, ".rzip");

因此您知道发生分段错误的确切行。

在现代发行版中生成core 文件变得更加复杂,因为将对core 文件的控制权转移到systemd。根据您的发行版,您可能会使用coredumpctl 实用程序来检索核心文件。

【讨论】:

    【解决方案2】:

    您的 char *outname 没有分配足够的内存来容纳连接的字符串。

    在下面使用:

       char *str2 = ".rzip";
    char * outname = (char *) malloc(1 + strlen(name)+ strlen(str2) );
    strcpy(outname, name);
    strcat(outname, str2);
    
    fp = fopen(name, "r");
    wp = fopen(outname, "w");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      相关资源
      最近更新 更多