I am having problems with the checking of the bounds of malloc. I have an if statement in my function saying if the address of top equals the last part of malloc, to print that the stack is full. When I test it, though, it just keeps going past it. Any idea why?
Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
int add(int ** top, int * stack);
int pop(int **top, int * stack);
int main()
{
int *stack = NULL;
int *top = NULL;
stack = (int *)malloc (SIZE * sizeof(int));
top = stack;
int b = 0;
int (*f[])(int ** top ,int * stack) = {add, pop};
while (b < 2)
{
printf("The address of stack is %d\n", stack + 5);
printf("What would you like to do?\n");
scanf("%d", &b);
f[b]( &top , &stack);
printf("The address that TOP points to is %d\n", top);
}
}
int add(int ** top, int * stack)
{
int a = 0;
if ( *top == stack + 5)
{
printf("The address of *top is %d ", *top);
printf("The stack is full.");
}
else
{
printf("The address that TOP points to is %d\n", *top);
printf("Please enter a number to stack, push 0 to quit this operation.");
scanf("%d", &a);
**top = a;
printf("The number put on the stack was %d\n", **top);
++ *top;
printf("the address of top is now %d\n", *top);
}
}
int pop(int **top, int * stack)
{
if (*top == *stack - 1)
printf("The stack is already empty.\n");
else
{
printf("The number that was just popped was %d", **top);
-- *top;
}
}