0

I've got the following example :

#define MAX_SIZE 32 

typedef struct T {
     int total_data;
     D *data;
} T;

typedef struct D {
     int type;
     char value[MAX_SIZE];  
} D;

I've got a part which extract and fill D* data; And one who print it.

The part which extract and fill D extract data from a file.

void extract(T *_t) {
     // Open file
     fscanf(fp, "%d\n", &_t->total_data);
     _t->data = malloc(_t->total_data * sizeof(*_t->data);

     // Extract and fill 
     for ( i = 0; i < _t->total_data; i++) 
         fscanf(fp, "%d:%[^$]\n", &(_t->data[i].type), _t->data[i].value);
 }

The function which read looks like this :

void read(T *_t) {
    int i; 
    for( i = 0; i < _t->total_data; i++) 
         printf("%d - %s", _t->data[i].type, _t->data[i].value);
}

But I've got a crash .. I don't know why .. the code looks ok for me according to what I've found on the web. Could you please help me ?

Thanks.

Files look like that :

2
0:ABC
1:DEFGHI

For exemple

2
  • I have only looked at the code so far... always make sure malloc hasn't returned NULL. Especially given the fact you're reading from a file, you could run out of memory. Always assume you might run out of memory anyway :) Commented Oct 14, 2019 at 23:09
  • Possible duplicate of Freeing array of structs inside struct Commented Oct 15, 2019 at 7:44

1 Answer 1

1

This line:

fscanf(fp, "%d\n", _t->total_data);

is invalid. _t->total_data is an int but you need a pointer to int in order to scan data.

Try

fscanf(fp, "%d\n", &_t->total_data);
                   ^
                   note

BTW: Didn't your compile give a warning for this ?

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

2 Comments

Well .. nope he did not >< I'll take a look ! Thanks
@kaldoran do you use the flags -Wall -Wextra with your compiler? Works with gcc g++ and clang (maybe others compilers too)

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.