【问题标题】:Unable to debug - failed to use stack无法调试 - 无法使用堆栈
【发布时间】: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


【解决方案1】:

如果你发现无法调试,你应该做两件事:

  1. 检查您是否能够在您的环境中调试其他现有程序。这将排除环境问题而不是相关代码的问题。

  2. 注释掉程序中除了极少数行之外的所有内容,以便程序运行。然后,有选择地取消注释行,直到您将问题隔离到特定行。

将问题隔离到一行后,您就可以对特定问题进行互联网搜索。

【讨论】:

  • 我会尝试这样做。谢谢你的帮助
猜你喜欢
  • 2016-08-20
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多