分段错误,解析,C

时间:2014-03-28 08:45:31

标签: c parsing csv

我正在编写一个c文件,它从.csv文件中获取信息,解析它,然后删除任何已解析的文件。我遇到的问题是,在它运行.csv文件的一行后,我得到一个分段错误。我听说我可以使用GDB来帮助解决这个问题,但我不知道如何使用它。这是我的.c文件

void parser(int argc, char ** argv)
{
FILE * songList;
char * theString;
char * theToken;
char songs[ROOM_STRING_LENGTH];
char artist[ROOM_STRING_LENGTH];
char title[ROOM_STRING_LENGTH];
int x;
int length;
double size;
char * type;
char songType[1];
char songTypeC;
MusicRec * next;

theToken = "";


songList = fopen(argv[1], "r");

if(songList == NULL)/*returns an error if file wasnt opened*/
{
    printf("error opening file\n");
}

else
{
    while(fgets(songs, ROOM_STRING_LENGTH, songList) != NULL)/*gets one string at a time until fgets equals NULL*/
    {
        theString = malloc((sizeof(char)*(strlen(songs)+1))); /* mallocs some memory*/
        strcpy(theString, songs);
        x = 0;
        for(theToken = strtok(theString, ","); theToken; theToken = strtok(NULL, ","))
        {
            switch(x)
            {
                case 0:
                strcpy(artist, theToken);
                printf("%s\n", artist);
                break;

                case 1:
                strcpy(title, theToken);
                printf("%s\n", title);
                break;

                case 2:
                sscanf(theToken, "%d",&length); 
                printf("%d\n", length);
                break;

                case 3:
                size = atof(theToken);
                printf("%.2f\n", size);
                break;

                case 4: 
                type = malloc(sizeof(char));
                sscanf(theToken, "%s",type);
                songType[0] = *type;
                songTypeC = songType[0];
                printf("%c\n", songTypeC);
                free(type);
                break;
            }
            x++;

        }
        next = malloc(sizeof(MusicRec));
        next = createRecord(title, artist, size, length, songTypeC);
        /*print = printRecord(toPrint);*/
        destroyRecord(next);  
        /*free(print);*/
        free(next);
    }

free(theString);
free(theToken);
fclose(songList);

}
}

这些是被称为的两个函数:

char * printRecord(MusicRec * toPrint)
{
char token[ROOM_STRING_LENGTH];
char * pointer;

sprintf(token, "%s (%s):%d[%.2f]", toPrint->title, toPrint->artist, toPrint->lengthInSeconds, toPrint->sizeInKB);
pointer = malloc(sizeof(char)*strlen(token));
strcpy(pointer, token);
return(pointer);
}


void destroyRecord(MusicRec * theRecord)
{
free(theRecord->title);
free(theRecord->artist);
}

1 个答案:

答案 0 :(得分:0)

看一下这段代码:

case 4: 
  type = malloc(sizeof(char));
  sscanf(theToken, "%s",type);

您正在分配一个1字节的字符串并将任意长度的字符串读入其中。 如果输入令牌大于1,则容易出现段错误。