简体   繁体   中英

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. 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.

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;
}

Your char *outname does not have enough memory allocated to accomadate the concatenated string.

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. You are misusing strcat on a character string constant.

To quickly debug segmentation faults in Linux you should use the core dump facility provided by the OS.

It is plain simple:

  1. Compile with -g option

    $ 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

    $ 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 ./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 . Depending on your distribution you might use coredumpctl utility to retrieve core files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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