0

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.

Paul
  • 1,630
  • 1
  • 16
  • 23
  • 2
    We need to see how `add_head` is being used. What's being passed to it? Also, what do you mean you want the function to modify `P`? Modify it how? Your questions is unclear. You need to provide a [minimal, complete, verifiable example](https://stackoverflow.com/help/mcve). – Carey Gregory Oct 21 '18 at 22:41
  • 2
    Note the discussion in [Is it a good idea to typedef pointers](https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers) — TL;DR, no, except perhaps for function pointers. Also note that the dot `.` and arrow `->` operators bind very tightly and conventional C formatting demands that they should not be surrounded by spaces. Conventional C formatting uses either Allman (my preference) or 1TBS indentation, and not the Pico style you're using. See Wikipedia on [Indentation styles](https://en.wikipedia.org/wiki/Indentation_style). – Jonathan Leffler Oct 21 '18 at 23:06

1 Answers1

0

I would like the (add_head) function to modify P and not to return a new pointer.

If you are adding a new element to the structure, you need to allocate memory for this new element.

If this new element should be added at the head of a list, then the head pointer will change to the new location.

Old List with A,B,C
 ___       ___       ___       ______ 
| A | --> | B | --> | C | --> | NULL |
|___|     |___|     |___|     |______|
 Head

New List after adding element D
 ___       ___       ___       ___       ______ 
| D | --> | A | --> | B | --> | C | --> | NULL |
|___|     |___|     |___|     |___|     |______|
 Head

The second function that you wrote (with malloc) is necessary.

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31