i have this function and dont work, in ubuntu show me Segmentation fault (core dumped)
when i call the function:
void loadSavedGame(char fileName[], struct saveGame *savedGamesReaded[], int *length, int *statusCode){
char line[500];
char *token2;
int x=0;
*savedGamesReaded = (struct saveGame*)malloc((*length)*sizeof(struct saveGame)); //reserve memory for pointer and array elements
int j;
for(j=0; j<*length; j++){
(*savedGamesReaded)[j].id = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].score = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].position = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].maze_level = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].achievements = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].time_playing = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].virtual_players = (char *)malloc(MAX_STRING*sizeof(char));
}
while (feof(file) == 0){ //file its a text plane was opened before
fgets(line,500,file);
token2 = strtok(line,":"); // Here the program falls on the fourth loop
strcpy((*savedGamesReaded)[x].id, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].score, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].position, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].maze_level, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].achievements, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].time_playing, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].virtual_players, token2);
x++;
}
fclose(archivo);
}
I declared the struct so:
struct saveGame{
char *id;
char *score;
char *position;
char *maze_level;
char *achievements;
char *time_playing;
char *virtual_players;
};
I think the strtok
is not working, but i do not know why, maybe the NULL
in the token that's wrong?
strcpy((*savedGamesReaded)[x].id, token2);
token2 = strtok(NULL,":");