Reputation: 497
I am new to C. I am familiar with Python, Java, C#. As such, I am having problems with pointers.
I am attempting to implement a linked list in C using structs. As of now the program creates the root member, then adds one more member to have a list of 2 linked members. It then calls the print method that should loop through each item and print them. Unfortunately, the program is stuck in an infinite loop and appears to be printing the member->data addresses instead of the data itself.
As I said earlier, I am familiar with a few OOP languages. This problem is frustrating because a simple linked list is something I should be able to hammer out in a few minutes. Any help? The code is below.
#include<stdio.h>
#include<stdlib.h>
struct Member{
int data;
struct Member *next;
};
struct Member *createMember(int i){
struct Member *new;
new = malloc(sizeof(struct Member));
new->data = i;
return new;
}
void print(struct Member *root){
struct Member *current = root;
while(current->next != NULL){
printf("%i, ", current->data);
current = current->next;
}
printf("%i", current->data);
}
main(){
struct Member *root;
root = createMember(15);
root->next = createMember(12);
print(root);
}
Upvotes: 2
Views: 1493
Reputation: 66244
This function:
struct Member *createMember(int i)
{
struct Member *new;
new = malloc(sizeof(struct Member));
new->data = i;
return new;
}
allocates space and assigns your data, but never initializes the next
member. The result is that member containing indeterminate data, and therefore invoking undefined behavior to even evaluate, much less dereference, the former of which is done here:
void print(struct Member *root)
{
struct Member *current = root;
while(current->next != NULL){ // HERE
printf("%i, ", current->data);
current = current->next; // AND HERE
}
printf("%i", current->data);
}
To address the immediate problem change your allocation function to initialize all members:
struct Member *createMember(int i)
{
struct Member *new;
new = malloc(sizeof(struct Member));
new->data = i;
new->next = NULL; // ADDED THIS
return new;
}
Output
15, 12
Other issues remain (memory leaks, the behavior of print()
being passed a NULL pointer, more pedantic error checking, etc), but that is the most pressing related to your question.
Best of luck.
Upvotes: 6