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;
}