Why won't my program work?
I tried to make a linked list and it won't work, what's wrong with it?
Code:
#include <stdio.h>
void main(void)
{
struct node
{
char *name;
int count;
struct node *next;
};
struct node root = {"Start", 1, 0};
while(root.count < 20)
{
root->next = malloc(sizeof(root));
root.name = "Benny Hill";
root.count += 1;
root->next = NULL;
}
while(root != NULL)
{
printf("%s", root.name);
root = root->next;
}
}
Re: Why won't my program work?
Code:
while(root.count < 20)
{
root->next = malloc(sizeof(root));
root.name = "Benny Hill";
root.count += 1;
root->next = NULL;
}
There are also some problems here. I'd like to focus on the logic errors, so I will fix the grammar:
Code:
while( root.count < 20 )
{
root.next = (struct node *) malloc( sizeof(root) );
strncpy( root.name, "Benny Hill", sizeof(root.name) );
root.count += 1; /* could also be root.count++ if you prefer */
root.next = NULL;
}
I suspect you intended to a) allocate memory for a new node structure, b) point 'next' to the newly allocated memory, c) name the new link entry "Benny Hill", d) set 'count' in the new structure to be one greater than the current count, and e) set the new structure's 'next' pointer to NULL.
If we look carefully at the block of code, we see that you do indeed allocate memory for a new list element, and give it a 'name'. Then, instead of incrementing the count in the new element, you increment the count in the original element. Remember that 'root' is the original element and, for reasons quzah pointed out, 'root' will always be the original element (it is not a pointer you can step through the list with). Then you set 'next' (which was just pointed to the new element) to NULL. You allocate memory on the heap and then set the only pointer to that memory to NULL, which creates a memory leak (the allocated memory is simply 'forgotten', not freed). You then loop through this all over again starting with the same 'root' structure (creating and losing a whole new area of memory).
All hope is not lost. Make root a pointer you can step through your list with and be sure step through your list while allocating new nodes so you don't create memory leaks.
Best of luck.