0

This is my code below in C. I am attempting to read from file.txt with 2 columns: artist id and artist name, which are separated by a tab character.

Using structs to manipulate a linked list is the idea. It's fine when I use gcc -o. When I run ./, then I get abort 6.

struct artist
{
    int artist_id;
    int altartist_id;
    int playcount;
    struct artist *next;
    char artistname[lenName];

};

    struct artist *read_artists(char *fname)
        {
            int maxlen = 225;

            int artid = 0;
            int altartid = 0;
            int pc = 0;
            char artname;

            char data[maxlen];
            int valid = 0; // 0 acts as true 1 acts as false
            int checkresult = 0; //checks result of sscanf



            FILE *fp = fopen(fname ,"r");

            struct artist *temphead = create_artist(0,0,0,"0");
            print_artist(temphead);

            while (fgets(data,maxlen,fp))
            {
                checkresult = sscanf(data,"%d\t%[^\t\n]\n",&artid,&artname);

                if (checkresult == 2)
                {
                    struct artist *b = NULL;
                    b = create_artist(artid,altartid,pc,&artname);

                    temphead = add_artist(temphead,b);
                }
                else
                {   printf("break out of loop valid = 1\n");
                    valid = 1; // acts as boolean variable
                    break; //breaks out of the while(fgets)
                }
            }

            fclose(fp);

            return (temphead);
        }

added upon request

struct artist *create_artist(int artistid,int altartistid,int playcount,char *artistname)
{
    struct artist *a = NULL;
    a = ((struct artist *)malloc(sizeof(struct artist)));

    if (a != NULL)
    {
        a->artist_id = artistid;
        a->altartist_id = altartistid;
        a->playcount = playcount;
        strcpy(a->artistname,artistname);
        a->next = NULL;

    }

    return (a);
}
ProtectorOfUbi
  • 317
  • 5
  • 13
  • After `FILE *fp = fopen(fname ,"r");` check if `fp` is `NULL` and abort if yes. That means that the file couldn't been opened, possibily because it dosen't exist or it is not in the exepected directory. If you use `fgets(data,maxlen,fp)` with `fp` being `NULL`, you get undefined behaviour (most likely a crash). – Jabberwocky Nov 23 '15 at 13:48
  • 7
    `char artname;` is not a string. You need space to hold the text: `char artname[1234];` – 001 Nov 23 '15 at 13:48
  • You are probably writing to memory you do not own, see this post: http://stackoverflow.com/questions/29401116/abort-trap-6-in-c-program. – terence hill Nov 23 '15 at 13:49
  • Please show the `create_artist` function. – Jabberwocky Nov 23 '15 at 13:49

0 Answers0