Hỏi về signal SIGTRAP khi debug code C

chào mọi người. Cho em hỏi về thông báo lỗi signal SIGTRAP (trace/breakpoint trap) khi debug code trong C. Cụ thể là khi em debug code dưới đây thì đến dòng free(stack); thì gặp lỗi. Với cả mọi người xem cách cài đặt stack như dưới đây có ổn và có thể tối ưu nữa không. Em cảm ơn.

#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-1) 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{
        
        --*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("%c",stack[1]);
    free(stack);
    return 0;
}

Mình thấy có vấn đề gì đâu nhỉ. :thinking:


Nếu muốn ổn hơn thì bạn nên xây một struct Stack riêng ra. :slight_smile:

typedef char StackType;

typedef struct Stack {
    int top;
    unsigned int capacity;
    StackType *stack;
} Stack;

void init(Stack *st, int cap);
int empty(Stack *st);
int full(Stack *st);
void push(Stack *st, StackType val);
void pop(Stack *st);
void freeStack(Stack *st);
4 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?