0

This works:

struct list
{
    int value;
    struct list *next;
};

void addElement(struct list **l, int value)
{
    if( *l == 0 )
    {
        *l = (struct list *) malloc(sizeof(struct list));
        (*l)->value = value;
        (*l)->next = 0;
    }
    else
    {
        struct list *new_element = (struct list *) malloc(sizeof(struct list));
        new_element->value = value;
        new_element->next = *l;
        *l = new_element;
    }
}

void printList(struct list *l)
{
    struct list *temp;
    for(temp = l;temp; temp = temp->next)
    printf("%d ->", temp->value);
    printf("%d",0);
}

int main(int argc, char **argv)
{
    printf("Einfache verkettete Liste: ");
    struct list *mylist;    
    int i;

    addElement(&mylist,10);
    addElement(&mylist,10);
    addElement(&mylist,10);
    addElement(&mylist,10);
    addElement(&mylist,10);
    addElement(&mylist,10);
    addElement(&mylist,10);
    addElement(&mylist,10);
    addElement(&mylist,10);
    addElement(&mylist,10);

    printList(mylist);

    return 0;
}

Output:

Einfache verkettete Liste: 10 ->10 ->10 ->10 ->10 ->10 ->10 ->10 ->10 ->10 ->0

But if I change:

addElement(&mylist,10);
addElement(&mylist,10);
addElement(&mylist,10);
addElement(&mylist,10);
addElement(&mylist,10);
addElement(&mylist,10);
addElement(&mylist,10);
addElement(&mylist,10);
addElement(&mylist,10);
addElement(&mylist,10);

to:

for(i=0;i<10;i++)
    addElement(&mylist,10);

it gives a memory error on runtime? Its very confusing, i have no idea whats going on. How to debug?

flo
  • 199
  • 1
  • 12
  • 3
    Please **[do NOT cast the return value of `malloc()`!](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)** –  Sep 17 '13 at 17:56
  • Fixed this in my code, thanks! – flo Sep 17 '13 at 18:20

1 Answers1

8

You never initialized mylist to null, so the first time you call addElement, it's a matter of luck whether or not the *l == 0 is true. Seemingly irrelevant rearrangement of the code changes your luck.