Trouble with stack implementation

Member
Posts: 185
Joined: 2005.02
Post: #1
Ok, I know this is probably a really stupid question but I have been try to figure out how my thinking is flawed for about half an hour. I'm so angry that I 'm probably not thinking straight. My program gets to a point, then crashes.
relevant code:
Stack.h:
Code:
typedef struct StackItem
{
    [item]
    struct StackItem * lower;
    struct StackItem * higher;
} StackItem;

typedef StackItem * Stack;
Stack.c:
Code:
int pushOntoStack (Stack * pstack, [item])
{
    StackItem * pnew;
        
    pnew = (StackItem *) malloc(sizeof(StackItem));
    if (pnew == NULL)
        return 0;
    
    (*pstack)->higher = pnew; /*This is where the program crashes*/
    pnew->[item] = [item];
    pnew->lower = *pstack;
    pnew->higher = NULL;
    *pstack = pnew;
    
    return 1;
}
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #2
Is this supposed to be valid C? What are the random square brackets doing?
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #3
I'd say it's likely that *pstack is NULL. This would happen if you're pushing onto an empty stack. What you'd need to do is this:
Code:
if (*pstack)
    (*pstack)->higher = pnew;
Quote this message in a reply
Member
Posts: 185
Joined: 2005.02
Post: #4
akb825 Wrote:I'd say it's likely that *pstack is NULL. This would happen if you're pushing onto an empty stack. What you'd need to do is this:
Code:
if (*pstack)
    (*pstack)->higher = pnew;
Gah! So simple!

Thanks, it works now.
Quote this message in a reply
Nibbie
Posts: 2
Joined: 2006.10
Post: #5
Is (*pstack) even a pointer to a memory address? How is the Stack type defined?
Quote this message in a reply
Sage
Posts: 1,403
Joined: 2005.07
Post: #6
belthaczar Wrote:Is (*pstack) even a pointer to a memory address? How is the Stack type defined?
thats called dereferencing a pointer, it returns the 'value' of the object given the pointer value.

Sir, e^iπ + 1 = 0, hence God exists; reply!
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #7
I don't think that's what he was asking. He was wondering if pstack, or what pstack was pointing to, was valid in the first place, and what exactly it's supposed to represent. From what I understand, (*pstack) is a pointer to the top of the stack, while he sent the address into the push function (to get pstack) so he could modify it. What I caught was that when the stack is empty, the top of the stack is NULL, which he was dereferencing. (judging from the times, belthaczar may not have seen ferum's post saying my fix worked before posting his)
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Previous frame inner to this frame (corrupt stack?) wyrmmage 9 7,427 Nov 29, 2006 05:14 PM
Last Post: wyrmmage