Delete struct from stack memory

11,939

As others have said, you can't.

If you want to be able to store both allocated (by malloc) and non-allocated (static or automatic) storage objects in your list and have a "delete" function that removes objects from the list and frees them, you need to store as part of each list member a flag indicating whether it's in allocated storage or not, and only free the ones which are.

Also note that you'll be in big trouble if the lifetime of the structure with automatic storage ends before you remove it from the list! If dealing with this is confusing at all for you, then you would probably be better-off just using allocated storage (malloc) for all list members.

Share:
11,939
user2263786
Author by

user2263786

Updated on June 04, 2022

Comments

  • user2263786
    user2263786 almost 2 years

    I have a linked list struct, i want to pass one node (another struct) pointer to a function (the node is part of the linked list, but i'm passing the node seperately to a deleter function

    I want it to copy the next node data into itself (overriding its data), and to delete the next node, thus deleting itself (this part is working).. I made it check whether the passed node is the last node in the list, and if so, to delete itself.

    I don't know how to delete structs from the stack (i know i can malloc() and free() it using the heap memory).

    #include <stdlib.h>
    #include <stdio.h>
    
    typedef struct {
        int data;
        struct node * next;
    }node;
    
    typedef struct {
        struct node * head;
    }linked_list;
    
    void print_list(linked_list * list) {
    
        node *current = list->head;
        while (current) {
            printf("Current node has %d\n",current->data);
            current = current->next;
        }
    }
    
    void delete_node(node * n) {
        node * next = n->next;
        if (next) {
            n->data = next->data;
            n->next = next->next;
        }
        else {
            *n =  NULL; /*This of course won't compile because assigning void* (null) to node variable
                                  but if i make n point to NULL, nothing will happen because i'm inside a function
                                  and the pointer is duplicated (the passed pointer will still work) */
        }
    }
    
    void main(){
        node first;
        node second;
        first.data = 1;
        first.next = &second;
        second.data = 2;
        second.next = NULL;
        linked_list l;
        l.head = &first;
        print_list(&l);
        delete_node(&second);
        print_list(&l);
    }