Suppose I have the following code:

typedef struct _SingleList {
    struct _SingleList *link;
    int data;
} SingleList;


SingleList *prepend(SingleList *list, int data) {
    SingleList a;
    SingleList *newNode = &a; // Note, here I assign memory using structure not malloc.
    newNode->data = data;
    newNode->link = list;
    return newNode;
}

As, you can see in above prepend function, I assign memory using address of a instead of malloc and it works perfectly, when I call prepend function. Here's a sample:

int main(void) {
    SingleList *list = NULL;
    list = prepend(list, 10);
    printf("%d", list->data);

    list = prepend(list, 20);
    printf("\n%d", list->link->data);

    list = prepend(list, 30);
    printf("\n%d", list->link->link->data);

}

So, how it works and if it works for others too, then why we use malloc() for linked list instead of simply assigning a structure.

有帮助吗?

解决方案

In the function prepend, the return value newNode is a pointer that points to a local variable a. When the function ends, it's undefined behavior to access it. It just happens to work in your machine in this simple code, you can't rely on it.

其他提示

It doesn't work. If it shows correct values then it is pure coincidence and the memory wasn't overwritten by something else or someone else. When the prepend() function exits, memory allocated for the a structure is freed. Memory for that structure is only available in local context.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top