简体   繁体   English

C中文件处理操作中的段错误?

[英]Segmenation fault in file handling operations in C?

I'm a newbie to file handling in UNIX, and I can't figure out where and how I'm getting a segmentation fault. 我是UNIX中文件处理的新手,我不知道在哪里以及如何遇到分段错误。 Is there any memory that I'm not allocating or is it a problem with the actual opening and reading of the file. 是否有我没有分配的内存,或者实际打开和读取文件是否有问题? Note: There is an empty text file called "hi.txt" in the same directory. 注意:在同一目录中有一个名为“ hi.txt”的空文本文件。

read.c 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 main.c中

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

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

    return 0;
}

Your char *outname does not have enough memory allocated to accomadate the concatenated string. 您的char * outname没有足够的内存来分配串联的字符串。

Use below: 在下面使用:

   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");

BLUEPIXY's comment is spot on. BLUEPIXY的评论很明显。 You are misusing strcat on a character string constant. 您正在对字符串常量滥用strcat

To quickly debug segmentation faults in Linux you should use the core dump facility provided by the OS. 要在Linux中快速调试分段错误,应使用操作系统提供的核心转储工具。

It is plain simple: 很简单:

  1. Compile with -g option -g选项编译

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

  2. Remove the limit on core dump file size 取消核心转储文件大小的限制

    $ ulimit -c unlimited

  3. Run the program 运行程序

    $ ./read Segmentation fault (core dumped)

  4. Check that the core file has been generated 检查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. Run gdb on the core file 在核心文件上运行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");

Thus you know the exact line where the segmentation fault occurred. 因此,您知道发生分段错误的确切行。

On modern distributions generating the core files became more complicated with the transfer of control over core files to systemd . 在现代发行版中,随着对core文件的控制权转移到systemd生成core文件变得更加复杂。 Depending on your distribution you might use coredumpctl utility to retrieve core files. 根据您的发行版,您可以使用coredumpctl实用程序来检索核心文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM