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);
}
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);
}