简体   繁体   中英

Segmentation fault when writing to a file

UPDATED CODE FULLY FUNCTIONAL***

I'm new to C/C++ and I wrote a piece of code that would count the number of times the program has run by writing 'count' to a file each time. Except I'm getting a seg fault error when I try to run it. Anyone can tell me why ?

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

int main(int argc, const char * argv[]) {
    FILE *fp;
    printf("LINE 13 CLEAR");
    fp = fopen("MyPlayground.rtf", "r");
    int value;
    fscanf(fp, "%d", &value);
    printf("Value is %d", value);
    //printf("LINE 14 CLEAR");
    if(fp== NULL)
    {
        printf("LINE 17 CLEAR");
        if(fopen("MyPlayground.rtf", "w")==NULL)
        {
            exit(0);
        }
        //fprintf(fp,"%d",0);
        fclose(fp);
        return 0;
    }
    //printf("LINE 25 CLEAR");
    fp = fopen("MyPlayground.rtf", "w");
    //printf("LINE 30 CLEAR");
    fprintf(fp,"%d",++value);
    fclose(fp);
}

EDIT: The program runs until "printf("LINE 17 CLEAR");" and after that it gives me an 'EXC-BAD-ACCESS' error in the following line.

EDIT1: Fixed fixed the two different paths

EDIT2: Added error check for second fopen(...) statement.

Also, feel free to comment on any style errors and things I should/should not do. Thanks.

I bet it only happens a first time you run it. The reason why is line 11:

11 fprintf(fp, 0);

You are basically passing fprintf a null pointer. What you probably meant to do was this:

11 fprintf(fp, "0");

Here is how I figured it out. I compiled it with debug info and ran it using debugger... lldb, to be precise:

(lldb) bt * thread #1: tid = 0xacaaf, 0x00007fff90f4dcf6 libsystem_c.dylib __vfprintf + 327, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0) * frame #0: 0x00007fff90f4dcf6 libsystem_c.dylib __vfprintf + 327

frame #1: 0x00007fff90f762e7 libsystem_c.dylib`__v2printf + 471

frame #2: 0x00007fff90f766bc libsystem_c.dylib`__xvprintf + 633

frame #3: 0x00007fff90f4db36 libsystem_c.dylib`vfprintf_l + 54

frame #4: 0x00007fff90f4669b libsystem_c.dylib`fprintf + 186

frame #5: 0x0000000100000e9d test.out`main(argc=1, 

argv=0x00007fff5fbffc60) + 109 at test.c:11 frame #6: 0x00007fff8f9c95fd libdyld.dylib`start + 1

...if you look at frame 5, you will see the offending line of code.

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