我很好奇如何刪除存儲在列表中的結構。 我試過這段代碼,但它給了我一個分段錯誤錯誤,我看不到錯誤。free()struct **指針的值
typedef struct double_stack_head_struct
{
struct double_stack_head_struct* tail;
double value;
} double_stack_head;
typedef struct double_stack_struct // the structure containing the state of a stack
{
int size; // size of stack
double_stack_head* head;
} double_stack;
void push_double_stack(double_stack* stack, double value)
{
double_stack_head* new_head = malloc(sizeof(double_stack_head));
if(new_head != NULL) {
new_head->tail = stack->head;
new_head->value = value;
stack->head = new_head;
stack->size += 1;
}
}
int pop_double_stack(double_stack* stack, double* value)
{
if(empty_double_stack(stack)) {
return false;
} else {
*value = stack->head->value;
free(stack->head);
stack->size -= 1;
stack->head = malloc(sizeof(stack->head));
stack->head = stack->head->tail;
return true;
}
}
你的彈出函數調用malloc,然後立即覆蓋保存的指針。這會泄漏,也可能是崩潰的原因(如果其他值不是malloc的有效指針)。 –
彈出後分配一個新頭也沒有多大意義。 –