Question

Update: Properly initialising string with char string[sizeof buffer - 1] has solved the crashing problem, but I'm still curious as to what having more than one punctuation mark had to do with it!

I am trying to read a string from a file in the form "some text". Using sscanf with the pattern \"%[^\"]\" has worked perfectly for me so far, but as soon as I started adding punctuation to the string the program has started crashing.

It seems that the error only occurs if more than one punctuation mark is used, regardless of what punctuation mark it is, or the mark's position. It also occurs regardless of the position of lines with punctuation in the file (ie. even if last line has no punctuation the error still occurs).

Anyway, below is the code I have so far:

char* func(char* f_name);
    FILE* file = get_file(f_name,"r"); // a short function I wrote to get the
                                       // file pointer from the current
                                       // directory. The error is almost
                                       // certainly not here.
    if (file == 0) {
        print("Unable to load file\nExiting...");
        exit(-1);
    }

    char* pattern = "\"%[^\"]\"";
    int read_args = -1;
    char* string; //  string size is unknown until read
    char buffer[1200]; // i expect very long line of data in the file

    while ( fgets( buffer, sizeof(buffer), file ) != NULL ) {
        printf("found line: %s\n",buffer);
        read_args = sscanf(buffer, pattern, string);
        printf("num args: %d\n",read_args);
        printf("read value: %s\n", string);
    }

    fclose(file);
    return string;
}

The following are some data I have tried. Where marked 'unsuccessful' the program compiles, runs everything, and the crashes just before exiting.

"test test test" // successful
"test, test test" // successful
"test test; test" // successful

"test, test, test" // unsuccessful
"test; test. test," // unsuccessful

I plan to use a more complex pattern if this problem is resolved, and was reading data with the pattern %d \"%[^\"]\" \"%[^\"]\" successfully before this error occurred. Thanks in advance for any answers.

Was it helpful?

Solution

Your code invokes undefined behavior, since you're scanning into random memory.

The string variable is never initialized, so the destination for the string written by sscanf() is undefined.

You need e.g.

char string[sizeof buffer - 1];

The fact that it doesn't always crash is just luck, the code is invoking undefined behavior all the time. It might just have been that with punctuation, based on your examples, the scanned text was longer and thus overwrote more memory, eventually triggering the crash once it hit something important enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top