【发布时间】:2019-11-10 08:07:26
【问题描述】:
我使用堆栈来处理字符,如下面的代码。 当我运行这个程序时,它不会在屏幕上打印任何东西。我试图调试,但它有错误“程序收到信号 SIGTRAP,跟踪/断点陷阱”。请帮助。谢谢你的帮助。
#include <stdio.h>
#include <stdlib.h>
short IsEmpty(int *top){
if (*top==-1) return 1;
return 0;
}
short IsFull(int *top, int capacity){
if (*top == capacity) return 1;
return 0;
}
void Push(int *top, int capacity, char *stack, char value){
if (IsFull(top, capacity)==1) printf("stack overflow");
else{
++*top;
stack[*top]=value;
}
}
void Pop(int *top, int capacity, char *stack){
if (IsEmpty(top)==1) printf("stack underflow");
else{
free(stack[*top]);
--*top;
}
}
int main(){
int top=-1;
int capacity;
printf("import capacity of stack: "); scanf("%d",&capacity);
char *stack=(char *)malloc(capacity*sizeof(char));
Push(&top, capacity, stack, 'A');
Push(&top, capacity, stack, 'B');
Push(&top, capacity, stack, 'C');
Pop(&top, capacity, stack);
Pop(&top, capacity, stack);
Push(&top, capacity, stack, 'D');
printf("%s",stack[1]);
free(stack);
return 0;
}
【问题讨论】:
-
在 main 放置断点尝试运行。您的代码中有严重的 UB,因此如果调试器开始执行,您将最终进入 segfault free(stack[*top]);
-
@P__J__ 我使用 free(stack[*top]) 因为我想删除 stack[*top] 的值。现在我知道这是错误的。那么如何才能完全删除它的值呢?
标签: c debugging data-structures stack