Billy
Billy

Reputation: 751

C string modification

I came across a confused problem when I program in C

when i use oldPacket.filename = "fallout.jpg" //i have a file called fallout.jpg,and a struct called oldPakcet with an char* type filename

The program ran very well

Now, I decide to let user to in put the filename and also check the existence of the file. I wrote the following function:

bool Searchfile(packet* ptr) {
    char userinput[100];
    fgets(userinput, sizeof (userinput), stdin); //non terminated input by fgets
    userinput[strcspn(userinput, "\n")] = 0;
    //printf("%d\n",strlen(userinput));
    ptr->filename = userinput + 4;//i skip the first 4 char since the correnct format is ftp <filename>
    printf("%s\n",ptr->filename);
    printf("%d\n",strlen(ptr->filename));
    ptr->filename[strlen(ptr->filename)] = '\0';
    if (access(ptr->filename, F_OK) != -1) {
        printf("exist\n");
        return false;
    } else {
        //printf("does not exist\n");
        return true;
    }
}

I call this function by

while (Searchfile(&oldPacket)){
    printf("Please input the file name in the format: ftp <file name> \n");
}

However the program is no longer working and it shows seg fault at

int filesize;
    fp = fopen(oldPacket.filename, "rb");
    fseek(fp, 0L, SEEK_END);//here is the seg fault

Anyone have some idea why this happen ?

I already printf each char of the filename and it looks correct....

Thanks in advance

Upvotes: 0

Views: 57

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35164

You let ptr->filename point to an address of local variable userinput, and accessing this value once userinput has gone out of scope is undefined behaviour.

The reason for the segfault is probably that the value of filename, when accessed outside of Searchfile, may be garbage, such that the file will not be opened. The subsequent fseek will then be called with a NULL-value for fp...

A simple solution to overcome this would be to write static char userinput[100];, at least when you are not working in a multithreaded environment. Otherwise you'd have to reserve memory for ptr->filename and copy contents of userinput.

Upvotes: 2

Related Questions