0

I'm attempting to use pointers to make this struct's data dynamically allocated.

struct Stack
{
    int top;
    ItemT *items;
    int size;
};

StackP newStack()
{
    struct Stack s;
    StackP p = &s;

    p->top = -1;
    p->items = malloc(sizeof(ItemT) * DEFAULT_CAPACITY);
    p->size = DEFAULT_CAPACITY;

    return p;
}

void pushStack(StackP p, ItemT i)
{
    p->top++;
    p->size--;
    p->items[p->top] = i;
}

I have to use an array, and it is being separated from the struct via a pointer so that I can expand it without having to expand the struct. When I run a test of pushStack(), I get a seg fault. I've identified the line "p->items[p->top] = i" to be the issue, but I don't know why. I suspect the memory allocated in my constructor might be inaccessible from other functions. First, why am I getting a seg fault? Second, how can I fix the issue? (These functions are prototyped / declared in a separated .h file)

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
Patrick Taylor
  • 112
  • 2
  • 11
  • what is `p->size--;` for? Another problem you may run into is having `p->top` be outside the bounds of how much memory you have allocated; you need to be careful about tracking this. – M.M May 20 '14 at 22:05

2 Answers2

4

The main problem is that you're returning a pointer to a local instance of Stack (s in this case), you should also dynamically allocate the instance you're going to return:

StackP newStack()
{
    StackP p = malloc(sizeof(struct Stack));

    p->top = -1;
    p->items = malloc(sizeof(ItemT) * DEFAULT_CAPACITY);
    p->size = DEFAULT_CAPACITY;

    return p;
}
xorguy
  • 2,594
  • 1
  • 16
  • 14
2

In your newStack function, you create the stack with:

struct Stack s;
StackP p = &s;

Unfortunately, as soon as the routine returns, the stucture s that p points to falls of the stack and goes away. You really should do:

StackP p = malloc(sizeof(struct Stack));

and then at the end of the program, free(p); to cleanup.

JohnH
  • 2,713
  • 12
  • 21