YiFeng
YiFeng

Reputation: 981

simple code with EXC_BAD_ACCESS

I am new to the objective c and i write the code according to a reference book. but something went wrong and I don't know why.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    if (argc==1){
        NSLog(@"you need to provide a file name");
        return (1);
    }

    FILE *wordFile = fopen(argv[1], "r");
    char word[100];

    while(fgets(word , 100, wordFile)){
        word[strlen(word)-1] = '\0';

        NSLog(@"the length of the %s is %lu", word, strlen(word));
    }
    fclose(wordFile);

    return 0;
}

the tool indicates that the while part went wrong, EXC_BAD_ACCESS.
Any idea?

Upvotes: 0

Views: 579

Answers (1)

simonpie
simonpie

Reputation: 354

It compiles and runs fine on my machine. But imagine you have an empty line in your file. Then strlen(word) will return zero. Hence word[strlen(word)-1] = '\0'; will try to set some memory which might not be valid since word[-1] might not be a valid memory cell, or a memory cell that you can legally access.

Oh, and by the way, it has nothing to do with objective-c. This is mostly (but for the NSLog call) pure ansi C.

Upvotes: 4

Related Questions