我有这个功能而且不工作,在我调用函数时,在ubuntu中显示Segmentation fault (core dumped)
:
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);
}
我声明了结构:
struct saveGame{
char *id;
char *score;
char *position;
char *maze_level;
char *achievements;
char *time_playing;
char *virtual_players;
};
我认为strtok
无效,但我不知道为什么,令牌中的NULL
可能错了?
strcpy((*savedGamesReaded)[x].id, token2);
token2 = strtok(NULL,":");
答案 0 :(得分:0)
这条线并没有按照你的想法行事:
while (feof(file) == 0){ //file its a text plane was opened before
feof()
仅在达到 EOF后返回true 。见Why is “while ( !feof (file) )” always wrong?
你永远不会检查这条线是否成功:
fgets(line,500,file);
另外,你不能关闭file
:
fclose(archivo);
答案 1 :(得分:0)
根据您的输入,token2 = strtok(<...>,":");
可以返回NULL
值,下一行会在尝试复制NULL
时产生段错误。您可以添加token2
的检查,如果它为NULL则中断。类似的东西:
fgets(line,500,file);
token2 = strtok(line,":");
if(!token2)
break;