0

The program has no problem in the push function as I can reach the members of the structure (e.g. key). If I call push(stack, 3) the key is 3 within the push function on the newElem pointer that has been allocated on the HEAP, but then when it is assigned to the stack, and used outside of push function (used in main), it no longer has a clue what values the members of the struct has at that current address. So it seems to me that the malloc doesn't really work and doesn't put the memory on the HEAP since It's not accessible anymore through the main function??

#include <stdio.h>
#include <stdlib.h>

typedef struct list_element_t {
    int key;
    struct list_element_t* next;
    struct list_element_t* prev;

}ListElement;

ListElement* GetNewElement(int k) {
    ListElement* newElem = (ListElement*) malloc(sizeof(ListElement));
    newElem->key = k;
    newElem->next = NULL;
    newElem->prev = NULL;
    return newElem;
}

void push(ListElement* S, int k) {
    ListElement* newElem = GetNewElement(k);

    //The key is always correct here
    printf("%d\n", newElem->key);
    if(S == NULL) {
        S = newElem;
        //S is not NULL here.
        return;
    } 
    newElem->next = S;
    S->prev = newElem;
    //Put our stack in the back of the list
    S = newElem;

}

void display(ListElement* S) {
    ListElement* temp = S;
    while(temp != NULL) {
        printf("%d\n", temp->key);
        temp = temp->next;
    }
}

int main(int argc, char **argv)
{
    ListElement* stack = NULL;
    push(stack, 3);

    //stack is still NULL here????


    //Causes segmentation Fault
    printf("%d\n", stack->key);


    //Never prints anything (stack is NULL)
    display(stack);
    return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
user2283719
  • 153
  • 2
  • 10

1 Answers1

1

S in push function is local variable, so in this assigment

S = newElem;

you assign newElem to temporary object which is destroyed when push ends. If you want to modify content pointed by S you should pass this by pointer to pointer.

void push(ListElement** S, int k) {
  ListElement* newElem = GetNewElement(k);

  printf("%d\n", newElem->key);
  if(*S == NULL) {
    *S = newElem;
    return;
  } 
  newElem->next = *S;
  (*S)->prev = newElem;
  *S = newElem;
}

and in main function call push function as follows

  ListElement* stack = NULL;
  push(&stack, 3);
rafix07
  • 20,001
  • 3
  • 20
  • 33
  • Thanks for the help, just to be clear. This is the same thing as, if you want to change an integer inside a void function. You have a pointer to an integer as a parameter and then you call that function with &integer? – user2283719 Feb 13 '18 at 16:56
  • exactly, it is the same case. – rafix07 Feb 13 '18 at 16:58