Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Help debugging stack program (http://www.velocityreviews.com/forums/t441199-help-debugging-stack-program.html)

White Spirit 02-06-2006 11:27 PM

Help debugging stack program
 
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);
}

Walter Roberson 02-06-2006 11:33 PM

Re: Help debugging stack program
 
In article <43e7db50$1@news1.homechoice.co.uk>,
White Spirit <white.spirit@ntlworld.com> wrote:
>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 ;-)
--
"law -- it's a commodity"
-- Andrew Ryan (The Globe and Mail, 2005/11/26)


All times are GMT. The time now is 06:44 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.