I have the following code, and on line 68, I’m getting a format error.
stack.c:68: warning: format ‘%e’ expects type ‘float *’, but argument 3 has type ‘double *’
On the input push 4, it gets a segfault. Not sure if they’re related. Please help!
#include <stdio.h>
#include <stdlib.h>
#define OFFSET '0'
#define DIM1 7
#define DIM2 5
#define RES_SIZE 1000
//typedef double double;
typedef struct {
double *contents;
int maxSize;
int top;
} stackT;
void StackInit(stackT *stackP, int maxSize) {
double *newContents;
newContents = (double *)malloc(sizeof(double)*maxSize);
if (newContents == NULL) {
fprintf(stderr, "Not enough memory.\n");
exit(1);
}
stackP->contents = newContents;
stackP->maxSize = maxSize;
stackP->top = -1;
}
void StackDestroy(stackT *stackP) {
free(stackP->contents);
stackP->contents = NULL;
stackP->maxSize = 0;
stackP->top = -1;
}
int StackIsEmpty(stackT *stackP) { return stackP->top < 0; }
int StackIsFull(stackT *stackP) { return stackP->top >= stackP->maxSize-1; }
void StackPush(stackT *stackP, double element) {
if(StackIsFull(stackP)) {
fprintf(stderr, "Can't push element: stack is full.\n");
exit(1);
}
stackP->contents[++stackP->top] = element;
}
double StackPop(stackT *stackP) {
if(StackIsEmpty(stackP)) {
fprintf(stderr, "Can't pop element: stack is empty.\n");
exit(1);
}
return stackP->contents[stackP->top--];
}
void StackShow(stackT *stackP) {
int i;
printf("[ ");
for (i = 0; i < stackP->top - 1; i++) {
printf("%e, ", stackP->contents[i]);
}
printf("%e ]\n", stackP->contents[stackP->top - 1]);
}
double shell(char* s1, double arg) {
printf("> ");
scanf("%s %f%*c", s1, &arg);
return arg;
}
int main() {
//char cmds[DIM1][DIM2] = {{"push"}, {"pop"}, {"add"}, {"ifeq"}, {"jump"}, {"print"}, {"dup"}};
stackT res;
StackInit(&res, RES_SIZE);
char cmd[DIM2]; double arg = 0;
arg = shell(cmd, arg);
if (StringEqual(cmd, "push")) {
StackPush(&res, arg);
StackShow(&res);
}
}
Just had a quick look on you code , I think after pushing the first element your stack top pointer is set to 0 .
Now in you StackShow() method you are accessing an invalid memory location from this line :
This is an off-by-one error for the array contents .