问题
I wrote to following code which does not work. The application crashes on the print method. Any idea where it goes wrong?
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int item;
struct LinkedList *Next;
} LinkedList;
int main()
{
LinkedList vaz;
vaz.item = 14123;
vaz.Next = 0;
add(&vaz,123);
add(&vaz,9223);
Print(&vaz);
return 0;
}
void Print(LinkedList* Val)
{
if(Val != 0){
printf("%i\n",(*Val).item);
Print((*Val).Next);
}
}
void add(LinkedList *Head, int value)
{
if((*Head).Next == 0 )
{
LinkedList sab;
sab.item = value;
sab.Next = 0;
(*Head).Next = &sab;
}
else{
add((*Head).Next,value);
}
}
回答1:
Your add method should allocate memory dynamically, you are using automatic allocation (local variables), which is freed when you 'leave' the function. This will cause an undefined behavior when you try to access this memory later on.
void add(LinkedList *Head, int value)
{
if((*Head).Next == 0 )
{
LinkedList sab; <-- need to be allocated dynamically
sab.item = value;
sab.Next = 0;
(*Head).Next = &sab;
}
else{
add((*Head).Next,value);
}
}
回答2:
You did not allocate heap memory to the Linked list you create. I think you should allocate memory on the heap when you add elements to the linked list. The linked list variable 'sab' is local to the method and so the memory get deallocated as soon as the function goes out of scope.
To add an element, you need to do as follows:
LinkedList *sab = (struct LinkedList*) malloc (sizeof(struct LinkedList));
if( sab != NULL )
{
sab->item = value;
sab->next = NULL;
}
For more details, you can refer: http://www.cprogramming.com/snippets/source-code/singly-linked-list-insert-remove-add-count
回答3:
add should dynamically allocate memory as follows:
void add(LinkedList *Head, int value)
{
if (Head == NULL)
return;
if((*Head).Next == NULL )
{
LinkedList *sab = malloc(sizeof(LinkedList));
if ( sab == NULL ) {
// Error: ran out of memory (really shouldn't happen, but could)
return;
}
(*sab).item = value;
(*sab).Next = NULL;
(*Head).Next = sab;
}
else{
add((*Head).Next,value);
}
}
Also, the recursive call is "overkill" in this case. A simple loop would suffice:
void add(LinkedList *Head, int value)
{
if (Head == NULL)
return;
while ((*Head).Next != NULL)
Head = (*Head).Next;
LinkedList *sab = malloc(sizeof(LinkedList));
if ( sab == NULL ) {
// Error: ran out of memory (really shouldn't happen, but could)
return;
}
(*sab).item = value;
(*sab).Next = NULL;
(*Head).Next = sab;
}
I'd likewise avoid the recursive call for printing:
void Print(LinkedList* Val)
{
while (Val != NULL) {
printf("%i\n", (*Val).item);
Val = (*Val).Next;
}
}
If you have a function which removes items from the list, you need to ensure that you do a free on the pointer to that item that's removed.
回答4:
Your LinkedList *Head doesn't have any memory First assign memory to it as given below-
LinkedList *Head = (struct LinkedList*)malloc(sizeof(struct LinkedList));
来源:https://stackoverflow.com/questions/21762488/pointers-n-linked-list-in-c