Your main bug is that you haven't initialized s
to point to anything. You set s->arr
using new
, but haven't done so for s
itself. You dereference s
when setting the size
, top
, etc, and also when checking top
. This is undefined behavior.
You need:
struct stack *s = new struct stack;
to fix this.
Also, always remember to check the allocated pointer(s) are not nullptr
before proceeding.
You also don't de-allocate the memory (using delete
), so you have a memory leak.
Also, you can use instead the defined true
and false
, instead of 1
and 0
, and change the return types to be bool
.
Here is a corrected version of your code with the mentioned changes:
#include <iostream>
struct stack {
int size;
int top;
int *arr;
};
bool isEmpty(struct stack *ptr) {
if (ptr->top == -1) {
return true;
}
return false;
}
bool isFull(struct stack *ptr) {
if (ptr->top == ptr->size - 1) {
return true;
}
return false;
}
int main(void) {
/* you have to initialize s to point to something */
struct stack *s = new struct stack;
/* check for nullptr */
if (s == nullptr) {
return EXIT_FAILURE;
}
s->size = 80;
s->top = -1;
/* array of 80 integers */
s->arr = new int[s->size];
/* check for nullptr */
if (s->arr == nullptr) {
return 1;
}
if (isEmpty(s)) {
std::cout << "the stack is empty
";
} else {
std::cout << "the stack is not empty
";
}
/* remember to de-allocate the memory -- in the reverse order */
delete[] s->arr;
delete s;
return 0;
}
Tip: always compile your code with some basic compilation flags to check for this sort of thing. For example, you might compile using at least:
g++ -Wall -Werror -Wextra program.cpp
Also, consider using valgrind
, which is a powerful tool for detecting memory leaks and uninitialized memory accesses.
A few extra notes:
- The code reads like a C program more or less, as pointed out in the comments, so consider whether you want to instead write it as a C program, or adapt it more to C++
- You could also instead declare
s
to be on the stack instead (struct stack s;
), access its fields in main
like s.size
, s.top
, etc and then pass s
in by its address (&s
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…