mardi 4 août 2015

Tiny Linked List error in C

I have this four files,

tinyll.c tinyll.h in /home/user/lib

test.c tinyll.h in /home/user/code

and compile with this instructions for create a static library libtinyll.a and use it.

; in lib
$ gcc -c tinyll.c
$ ar -cvq libtinyll.a *.o

; in code
$ gcc -o test test.c ../lib/libtinyll.a

Until here all is ok. But I don't know why I obtain segmentation fault because the lines from [CODE ERROR] but showElements work. The target is not pass code from test.c to tinyll.c for treat the tiny list linked. How fix that?

/////////////////////////////////// test.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "tinyll.h"

int main(int argc, char *argv[])
{    
    progname = argv[0];

    char *file = "fwords";
    int n;
    PTLL lsone = NULL;
    n = loadfileinTLL(file,&lsone);

    // work. good. 
    showElements(lsone);

    // [CODE ERROR]
    // Why here dont work?
    // segmentation fault, load the first word
    // but in the second crash.
    while (lsone != NULL) {
        printf("%s",lsone->word);
        lsone = lsone->next;
    }    
    return 0;
}

/////////////////////////////////// tinyll.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "tinyll.h"

void addElement(PPTLL lst, char data[])
{
    PTLL elemt;
    elemt = (PTLL) malloc(sizeof(TLL));

    if (elemt == NULL) {
        fprintf(stderr, "%s: insufficient memory.\n", progname);
        exit(1);    
    }

    if (*lst == NULL)
    {
        strncpy(elemt->word, data, 45);
        elemt->next = NULL;
        *lst = elemt;
    }
    else {
        // add in front of list
        strncpy(elemt->word, data, 45);
        elemt->next = *lst;
        *lst = elemt;
    }
}

void showElements(PTLL lst)
{
    while (lst != NULL) {
        printf("%s\n",lst->word);
        lst = lst->next;
    }
}

int loadfileinTLL(char *filepath, PPTLL plst) 
{
    FILE *f;
    if ((f = fopen(filepath, "r")) == NULL) {
        fprintf(stderr, "%s: error to load file %s.\n", progname, filepath);
        exit(1);
    }

    char buf[45]; int n=0;
    while (fgets(buf,sizeof(buf),f) != NULL) {
        char *nl;
        if ((nl = strchr(buf,'\n')) != NULL) {
            *nl = '\0';
        }
        addElement(plst,buf);
        n++;
    }

    fclose(f);

    return n;
}

//////////////////////////////////// tinyll.h

#include <stdio.h>
#include <stdlib.h>

#ifndef _TINYLL_
#define _TINYLL_

struct list {
    char word[45];
    struct list *next;
};

// Tiny Linked List
typedef struct list TLL;
typedef struct list *PTLL;
typedef struct list **PPTLL;
char *progname;

#endif



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire