A Whole Slew of problems with Linked Lists in C

Thread Starter

jakegwood

Joined Apr 13, 2011
29
#include <stdio.h>

struct Node
{
struct Node* next;
int data;
};

struct List
{
struct Node* head;
int size;
};

struct Node initNode(struct Node* nextNode, int x)
{
struct Node newNode;
newNode.next = nextNode;
newNode.data = x;
return newNode;
}

struct List initList()
{
struct List newList;
newList.head = NULL;
newList.size = 0;
return newList;
}

void insert(struct List* list, int x)
{
struct Node newNode = initNode(list->head, x);
list->head = &newNode;
list->size++;
}

void printList(struct List* list)
{
int k = 0;
struct Node *current = (*list).head;
while(current != NULL)
{
k++;
printf("%d\n", current->data);
current = (*current).next;
if(k>50)
{
break;
}
}
printf("The size of the list is %d",list->size);
}



int main()
{
struct List myList = initList();
insert(&myList, 5);
printList(&myList);
printf("The size is %d\n", myList.size);
int i;
for( i = 0; i < 10; i++)
{
insert(&myList, i);
}
printf("The size is %d\n", myList.size);
printf("%d\n", (myList.head)->data);
printf("%d\n", myList.head);
printList(&myList);
}

So here's my code. I am trying to implement a linked list. The main problem I have is with the printList. It only prints memory locations (as well as the other printf's in main that I added as tests). I've tried (*current).data which still only prints memory locations and I've tried *(current->data) which returns an error when I compile. After inserting the five, the printlist runs once, printing one memory location as expected, but then when I insert 10 more values in the for loop, then print again, I get an infinite loop and it ends up printing the same address infinitely. I tried adding that k so the printList will print a maximum of 50 times to prevent the infinite loop and that compiles fine, but when I run, the program prints one memory location (presumably the first printList) and then I get a Bus Error.

I am already a java programmer, but C is really giving me a hell of a time.
 

WBahn

Joined Mar 31, 2012
30,062
Please repost your code placing it between code tags like this:

[code=rich]
Your code goes here.
[/code]

I have an errand to run, but I'll be happy to look over your code when I get back in an hour or so.
 

AsmCoder8088

Joined Apr 17, 2010
15
jake,

The problem lies in your insert function. You are storing the address of a variable that is defined in local scope. Consequently, once the function returns, that address is meaningless and will just point to garbage.

If you change your insert function to the following:

Rich (BB code):
void insert(struct List* list, int x)
{
    //struct Node newNode = initNode(list->head, x);

    //list->head = &newNode;// using address of local variable
    //list->size++;


    struct Node *newNode = initNode(list->head, x);

    list->head = newNode;
    list->size++;
}
and then change your initNode function so that it returns a pointer to a Node:

Rich (BB code):
struct Node* initNode(struct Node* nextNode, int x)
{
    struct Node *newNode;

    newNode = (struct Node *)malloc(sizeof(struct Node));

    newNode->next = nextNode;
    newNode->data = x;

    return newNode;
}
Then your code will work. Here is the complete new code:

Rich (BB code):
#include <stdio.h>
#include <stdlib.h>

struct Node
{
    struct Node* next;
    int data;
};

struct List
{
    struct Node* head;
    int size;
};

struct Node* initNode(struct Node* nextNode, int x)
{
    struct Node *newNode;

    newNode = (struct Node *)malloc(sizeof(struct Node));

    newNode->next = nextNode;
    newNode->data = x;

    return newNode;
}

struct List initList()
{
    struct List newList;

    newList.head = NULL;
    newList.size = 0;

    return newList;
}

void insert(struct List* list, int x)
{
    //struct Node newNode = initNode(list->head, x);

    //list->head = &newNode;// using address of local variable
    //list->size++;


    struct Node *newNode = initNode(list->head, x);

    list->head = newNode;
    list->size++;
}

void printList(struct List* list)
{
    int k = 0;
    struct Node *current = (*list).head;

    while (current != NULL)
    {
        k++;
        printf("%d\n", current->data);
        current = (*current).next;

        if (k>50)
        {
            break;
        }
    }
}


int main(int argc, char *szArgv[])
{
    struct List myList = initList();
    int i;

    insert(&myList, 5);

    printList(&myList);
    printf("The size is %d\n", myList.size);

    
    for( i = 0; i < 10; i++)
    {
        insert(&myList, i);
    }

    printList(&myList);
    printf("The size is %d\n", myList.size);
    

    return 0;
}
The output of which looks like this:

Rich (BB code):
5
The size is 1
9
8
7
6
5
4
3
2
1
0
5
The size is 11
I will add that most implementations of linked-lists tend to insert elements such that they follow a first-in, first-out (FIFO) order. But yours works as well.
 

WBahn

Joined Mar 31, 2012
30,062
Let's examine your code piece by piece:

Rich (BB code):
// From main()
struct List myList = initList();

// Function called
struct List initList() 
{
   struct List newList;

   newList.head = NULL;
   newList.size = 0;
   return newList;
}
Here you are playing with fire because newList is an automatic variable in the function and it goes away when the function returns. However, whether by deliberation or by happenstance, you are okay because structures are returned by value and copied into the target structure just like regular variables. So what you've done is legitimate and does what you want, but it's important that you understand why both of those are true.

Rich (BB code):
// From main()
insert(&myList, 5);

// Function called
void insert(struct List* list, int x)
{
   struct Node newNode = initNode(list->head, x);
   list->head = &newNode;
   list->size++;
}

Here's the fire of which I spoke.

newNode is an automatic variable that is stored on the stack. It goes away when the function returns. Now, by 'go away', I mean that it is no longer valid to assume that the information stored at that address will remain unchanged because it becomes available to other functions automatically as they are called.

But, you store the address of this automatic variable in your structure and, hence, your linked list is expecting the information stored at that address to continue representing that data even after the function returns.

A big point to remember is that whenever you want to create new variables that stick around, you have to allocate memory for those variables using malloc() or one of the other handful of memory allocation functions. Otherwise, you are trying to store more and more data in a conceptually fixed amount of space and something has to give.
 

WBahn

Joined Mar 31, 2012
30,062
Interesting, didn't know about [plain], thanks for this.
I ran across that while looking for how to do something else.

In your reply, you should have escaped the [plain] text by entering it as [plain][plain][/plain]. What happens if you don't is that if someone quotes the text, as I did above, the parse sees the [plain] tag and it then stops parsing and doesn't parse again until it sees the [/plain] tag (if it ever sees one). As a result, none of the tags that weren't closed out before the [plain] was encountered, including the original [QUOTE] get executed.

But what if you want to display the [/plain] tag itself? You can't put it between a pair of noparse tags because the [/plain] tag is the one tag that the interpretter is sensitive to following a [plain] tag. It turns out that this isn't a problem because the interpretter doesn't interpret closing tags if there isn't a matching open tag that is active.

Other links that are very useful:

BB Code

Smilies

I found this list of Special Characters on Bill Marsden's blog, but I haven't figured out how to actually enter them. If I try holding down the 'Alt' key, as soon as I type anything else it is interpretted as a browser command to jump somewhere else on the page. So up until now I have been limited to finding the character I want and doing a copy-paste.

A bit of playing around has let me figure it out. You HAVE to use the numbers on the number pad and NOT the numbers in the top row of the regular keys. I assume this is the same for a laptop keyboard, which would be a royal pain in the ass. Also, the leading 0 is significant in that it must either be there or it must be absent.

For instance, if you use alt-0181 you get µ, but if you use alt-181 you get ╡. You alse get µ using alt-230, but I don't know if these are truly the same character in the character set. At first I assumed that the leading 0 marked the value as being octal and that, without it, the value was assumed to be decimal. But that doesn't seem to be the case since 0181 clearly isn't octal. So I don't know why the leading zero is significant.

One thing I wish the moderators would do would be to create a single Tex reference page and then consolidate all of the various stickies on this topic there and either have a single link at the top of the page or have a sticky in each forum (that is relevant) point to it. It gets frustrating having to hunt through several in order to find the useful tidbit that you previously found.

Tex sticky posts from:
General Electronics Chat
Homework Help

Actually, it appears that there are only these two, so it's not as bad as I had thought. I guess the fact that there are multiple, even if just two, creates the impression that there is a sea of them, especially when you try to look for things that you've seen before but aren't in either one of them, you start assuming it must be in yet another one that you can't find any more. I think this is what happened to me because I was trying to track down how to do a table like one I had seen in a post and I had assumed it was Tex, but I later discovered that it was BB Code.
 
Top