Help debugging stack program

W

White Spirit

The following program (code fragment but is supposed to work) which
implements three stacks segfaults when run and I can't for the life of
me think why. It worked perfectly before I changed it to use pointers,
and it doesn't get as far as printing the string in main.

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>

#define SIZEOFSTACK 100

struct stack
{
char value[SIZEOFSTACK];
int size;
} *controlStack, *resultStack, *memoryStack;

void pushToStack (char v, struct stack *ptrStack)
{
if (ptrStack->size < SIZEOFSTACK)
{
ptrStack->value[ptrStack->size] = v;
ptrStack->size++;
}

else

{
printf ("Error - stack out of bounds.\n");
}
}

char popFromStack (struct stack *ptrStack)
{
if (ptrStack->size == 0)
{
printf("Error - attempt to pop a value from an empty stack.");
/* Exception handling will go here */
}

else
{
return ptrStack->value[--ptrStack->size];
}
}

int main ()
{ printf ("got this far");
pushToStack('5', resultStack);
pushToStack('6', resultStack);
pushToStack('1', resultStack);
pushToStack('2', resultStack);

int i;

for (i = 1; i <=4; i++)
{
printf ("Popped %c\n", popFromStack(resultStack));
}
return (EXIT_SUCCESS);
}
 
W

Walter Roberson

The following program (code fragment but is supposed to work) which
implements three stacks segfaults when run and I can't for the life of
me think why. It worked perfectly before I changed it to use pointers,
and it doesn't get as far as printing the string in main.
#define SIZEOFSTACK 100

struct stack
{
char value[SIZEOFSTACK];
int size;
} *controlStack, *resultStack, *memoryStack;

Okay, non-automatic variables, so they will be initialized to 0.
So controlStack and resultStack and memoryStack start out as
NULL pointers.

The problem should be obvious now ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top