Search code examples
csegmentation-faultcyclescanf

sscanf cycle segmentation fault


I haven't programmed for a couple years and I have a question with sscanf:

I want to separate a string into several using sscanf, but sscanf gives me segmentation fault in a cycle. Why is that? how can I use sscanf in a cycle without happening?

Example:

int main() {
    char str[100];
    char mat[100][100]; int i = 0;
    strcpy(str, "higuys\nilovestackoverflow\n2234\nhaha");

    while (sscanf(str, "%s", mat[i]) == 1) i++;  
}

Solution

  • int sscanf(const char *str, const char *format, ...);

    while(sscanf(str,"%s",  mat[i]) == 1)  i++;
    

    Since str is constant in the prototype it cannot be changed by sscanf (unless sscanf is very broken :)), so it successfully repeats over and over, returning 1 all the time... So i increases, and at some point you're hitting a memory boundary and the system stops your harmful program.

    If you want to read a multi-line string, use a loop with strtok for instance, that will go through your string and yield lines.

    Note: my previous answer correctly assumed that the previous version question had a typo with an extra ; in the middle

    while(sscanf(str,"%s",  mat[i]) == 1);   i++;
    

    is always successful since str is the input and doesn't change (unlike when you're reading from a file using fscanf or fgets).

    So it was just an infinite loop in that case.