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)