Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign memory to structure using structure

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.

like image 943
Ashish Rawat Avatar asked Jun 06 '26 18:06

Ashish Rawat


1 Answers

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.

like image 126
Yu Hao Avatar answered Jun 08 '26 08:06

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!