I'm working on a LIFO stack structure, implemented as a singly linked list:
typedef struct spile {
char ch;
struct spile *address;
} Spile, *Pile;
and I want to code a push function which adds an element (char) to the head of the list.
Why does something like this lead to a core dump:
Pile add_head (Pile P, char c) {
P->address = P;
P->ch = c;
return P ;
}
While a similar function (this time deleting the head element) works?
Pile remove_head (Pile P) {
P = P->adress;
return P;
}
I know I can handle it like this :
#define MALLOC(t) ((t*)malloc(sizeof(t)))
Pile add_head (Pile P, char c) {
Pile P1 = MALLOC(Spile);
P1->address = P;
P1->ch = c;
return P1;
}
but I would like the function to modify P and not to return a new pointer. Moreover, since I'm not freeing (P1) anywhere the version above leads to a memory leak if I'm not mistaken.
edit: add_head is called like this
Pile my_pile = NULL;
my_pile = add_head(my_pile, 'z');
When I say I'd like to modify the parameter P in add_head I mean that P should be returned by the function but with the new element in it.