0

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

2
  • You return a pointer to a variable on stack that goes out of scope. Commented Oct 28, 2017 at 21:40
  • 1
    Also looking at the location of the seg fault, you may be interested in the value of "fp". Commented Oct 28, 2017 at 21:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.