Dpry12
Dpry12

Reputation: 105

C inserting into linked list, issue with first and last node

Below you will find my code, it is inserting properly anywhere in between the first and last nodes, but when I try to insert before the first node, or after the last, it is failing. I currently cannot figure it out, and was wondering if anybody could help. Thank you!

When I say it is not working, it does not fail out, it just will not insert at the first node or after the final node. There is no error message being thrown. I am thinking it may be an issue in the main body, vs the insert function

MAIN BODY (PORTION):

else{
        while (fgets(buff, BUFF_SIZE, stdin) != NULL){

            if (strlen(buff) == 1)
                break;

            buff[strlen(buff) - 1] = '\0';
            insertPnt = 1;

            // set curr = root node
            curr = root;
            while (curr){
                if (strcmp(buff, curr->stringDat) > 0){
                    insertPnt++;
                    curr = curr->next;
                }
                else{
                    insert(buff, insertPnt, root);
                    printf("STRING: %-20s  POSITION: %d\n", buff, insertPnt);

                    break;
                }
            }
            // clear buffer
            for (i = 0; i < BUFF_SIZE; i++) {
                buff[i] = 0;
            }
        }
    }

INSERT FUNCTION:

void insert(char* stringArg, int position, NODE* rootNodeArg){
    int i, strDatLen;

    /* Declaring node */
    NODE* temp = (NODE*)malloc(sizeof(NODE));

    strDatLen = strlen(stringArg);
    temp->stringDat = malloc(sizeof(char)*strDatLen);

    strcpy(temp->stringDat,stringArg);
    temp->next = NULL;



    /* if node insertion at first point */
    if (position == 1)
    {
        temp->next = rootNodeArg;
        rootNodeArg = temp;
        return;
    }

    /* Adding & Adjusting node links*/
    NODE* traverse = rootNodeArg;
    for (i = 0; i<position - 2; i++)
    {
        traverse = traverse->next;
    }
    temp->next = traverse->next;
    traverse->next = temp;

}

Upvotes: 0

Views: 51

Answers (1)

LPs
LPs

Reputation: 16243

You have a big problem with size of string

temp->stringDat = malloc(sizeof(char)*strDatLen);

must be

temp->stringDat = malloc( strDatLen+1);

To create space for null terminator.

As you can see on the man strlen return the number of chars into c-string noy counting the byte for the null terminator.

Upvotes: 1

Related Questions