October 22, 2024
Chicago 12, Melborne City, USA
C#

How to access the data inside a node whose memory location has been freed?


I am trying to return the data in the node after freeing the node. But I receive a segfault when I am trying to do that. (My guess is that when I assign the elem value to the variable data, it only copies the reference. After the memory location of the node freed, we lose the member elem inside the node struct. Therefore it is illegal to retrieve the elem via its reference.) Is there any other way of doing it?

void* remove_node(struct s_node** node){
    if(node != NULL && *node!= NULL && (*node)->elem != NULL){
        void* data = (*node)->elem;
        if((*node)->prev == NULL && (*node)->next == NULL){
            free(*node);
        }else if((*node)->prev == NULL){
            (*node)->next->prev = NULL;
            (*node)->next = NULL;
            free(*node);
        }else if((*node)->next == NULL){
            (*node)->prev->next = NULL;
            (*node)->prev = NULL;
            free(*node);
        }else{
            (*node)->prev->next = (*node)->next;
            (*node)->next->prev = (*node)->prev;
            (*node)->prev = NULL;
            (*node)->next = NULL;
            free(*node);
        }
        return data;
    }else{
        return NULL;
    }
}

And here is the struct

struct s_node {
    void* elem;
    struct s_node* next;
    struct s_node* prev;
};



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video