cstructstack-corruption

Error when reading a csv-file to a struct


I'm in trouble with reading a data from a csv-file and parsing it into a struct. I think its best to show some code.

This is my struct:

typedef struct MyStruct{
    char text[150];
    char attr[4][50];
    char check;
    short int num;
} t_mystruct;

A sample line in my file could look like this: This is a long text;brown;green;yellow;silent;X;13;

Now I want to read that file and add that data to an array:

list = malloc(sizeof(t_mystruct) * LIST_SIZE); /* Allocating Memory */

for (i = 0; i < LIST_SIZE; i++) /* Adding data to list */
{
    t_mystruct element;

    if (fscanf(fp, "%149[^;];%49[^;];%49[^;];%49[^;];%49[^;];%49[^;];%[^;];%d;", &element.text, &element.attr[0], &element.attr[1], &element.attr[2], &element.attr[3], &element.check, &element.num) != 7)
        break; /* Break ==> Incomplete line/data */

    list[i] = element;  /* Add to list */
}

This works, but I face two problems:

  1. The "num" value isn't the same value as in my file. I get results from 49 up to around 13000, but they never match my actual input value (13 in my example).
  2. The code belongs to a "readFile" function. At the end of that function, I face a "stack around the variable "element" was corrupted" error. Edit: When debugging, I can continue and the program works as expected.

But I can't see my mistakes.


Solution

  • You have specified five format specifiers of

    %49[^;];
    

    but your struct has only four, and you only provide four arguments to match. You are also reading the last value as int, when it is short.