【发布时间】:2019-04-04 22:14:19
【问题描述】:
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
struct stack {
// ... SOME CODE MISSING HERE ...
int top;
int stackArray[STACK_SIZE];
int push;
int pop;
};
struct stack *stack_init() {
struct stack* s = (struct stack*) malloc(sizeof(struct stack));
s->top = 0;
if (s == NULL)
return NULL;
else
return s;
}
void stack_cleanup(struct stack* s) {
for(int i = 0; i < STACK_SIZE; i++)
s->stackArray[i] = 0;
free(s);
}
int stack_push(struct stack *s, int c) {
if (s->top <= STACK_SIZE){
s->stackArray[s->top] = c;
s->top++;
s->push++;
return 0;
}
else
return 1;
}
int stack_pop(struct stack *s) {
if (!stack_empty(s)){
return s->stackArray[s->top];
s->top--;
s->pop++;
}
else
return -1;
}
int stack_peek(struct stack *s) {
if (!stack_empty(s)){
return s->stackArray[s->top];
}
else
return -1;
}
int stack_empty(struct stack *s) {
if (s->top == -1)
return 1;
else
return 0;
}
int main(){
struct stack *test;
// stack_peek(test);
// return 0;
printf("%d\n", test->top);
}
我正在尝试使用 C 为大学作业实现一个非常基本的堆栈,并且我正在尝试测试该实现,但它只给出错误 Segmantation fault (Core Dumped)。我在互联网上做了一些研究,但找不到可以帮助我的东西。我知道Segmentation Fault Core Dumped 意味着我正在访问我不能/不应该访问的东西,但我不知道这如何适用于我的代码。
谢谢。
【问题讨论】:
-
代码将取消引用未分配的
test指针。 -
@EugeneSh。所以test没有记忆?我如何将它分配到内存中的某个位置?
-
@user48719 您需要为您的结构分配内存,您刚刚创建了一个指针,该指针指向之前内存中的任何内容。尝试 malloc 为您的结构分配内存或 calloc 分配内存并将其归零。请注意,将内存归零需要一些时间,因此 malloc 将是更快的选择。
标签: c segmentation-fault stack