wpp
wpp

Reputation: 17

Problem my linked list

I am doing this homework task where it requires me to take in a massive string, and break this up into many substrings where each string is indicated by the '\n' new line value inside the string, and store this into a linked list, for example:

string = "hello world\n i need help!!"

Would turn into:

string1 = "hello world\n"
string2 = "i need help!!"

I've written up this code, that breaks the string into substrings and stores them into individual nodes. The code itself, is quite ugly and needs more refinement, but I can't even get to that point because somewhere weird seems to happen in the middle, where all the strings inside the linked list gets replaced by the last string I add to the linked list...

Here's my code, please help if you can:

#define eq(A, B) ( A == B )

typedef struct list * link;
typedef char Item;

struct list {
    link next;
    Item *string;
};


void printlist (link ls);
link newLS (char text[]);
link newNode (char text[]);
void insertNode (link next, Item item[]);

link newLS (char text[]) {
    int i = 0;
    int j = 0;
    char temp[(strlen(text))];
    link new = NULL;

    while (text[i] != '\0') {
        temp[j] = text[i];
        if (text[i] == '\n' || text[i+1] == '\0') {
            temp[j+1] = '\0';
            j = -1;
            if (new == NULL) {
                new = newNode(temp);
                printf("new: %s", new->string);
            } else {
                insertNode(new, temp);
                printf("new: %s", new->next->string);
            }
        } 
        i++;
        j++;
    }
    printlist(new);
    return new;
}

link newNode (char text[]) {
    link new = malloc(sizeof(*new));
    assert(new != NULL);
    new->string = malloc ((strlen(text)) * sizeof(char));
    new->string = text;
    new->next = NULL;

    return new;
}

void insertNode (link ls, Item item[]) {
    assert (ls != NULL);
    assert (item != NULL);

    while (ls->next != NULL) {
        ls = ls->next;
    }
    ls->next = newNode(item);

}

int main(int argc, char **argv) {
    link ls;

    ls = newLS("1\n2\n3");
    return 0;
}

We must use this function:

link newLS (char text[]) 

Upvotes: 0

Views: 223

Answers (1)

MByD
MByD

Reputation: 137272

  1. #define eq(A, B) ( A == B ) is not a good idea, an improvement will be to define it as #define eq(A, B) ( (A) == (B) )

  2. You allocate buffer, and then, not using it, but assigning another pointer to the pointer:

    new->string = malloc ((strlen(text)) * sizeof(char));
    new->string = text;
    

    instead, you should copy the data from the given pointer:

    new->string = malloc ((strlen(text) + 1) * sizeof(char));
    memcpy(new->string, text, strlen(text) + 1);
    

    moreover, when you'll try to free the allocated memory you'll get segmentation fault, because new->string is not pointing to the allocated area...

Upvotes: 1

Related Questions