You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Conditional Jump问题?队列代码触发Valgrind未初始化值报错

Conditional Jump问题修复方案

错误根源分析

Valgrind报告的"Conditional jump or move depends on uninitialised value(s)"来自两处未初始化问题,还附带一处逻辑bug:

  1. Queue结构体成员未初始化:main中用malloc分配Queue内存后,head和tail是随机垃圾值,input函数里if (!list->head)的判断依赖了未初始化的变量。
  2. stroka变量未初始化:main中int stroka;未赋值,第一次while(stroka != EOF)判断时使用了未初始化的垃圾值。
  3. 逻辑bug:原代码会把EOF也作为数据插入队列,不符合预期。

修复后的完整代码

#include <stdio.h>
#include <stdlib.h>

typedef struct Item {
    int data; 
    struct Item* next;
} Item;

typedef struct Queue{ 
    Item* head;
    Item* tail;
} Queue;

void input(Queue* list,int* stroka) {
    Item* new_node = (Item*)malloc(sizeof(Item));
    new_node->data = *stroka;
    new_node->next = NULL;
    if (!list->head) {
        list->head = new_node;
        list->tail = new_node;
    } else {
        list->tail->next = new_node;
        list->tail = new_node;
    }
}

// 补充实现print函数示例
void print(Queue* list) {
    Item* current = list->head;
    while (current != NULL) {
        printf("%c", current->data);
        current = current->next;
    }
}

int main() {
    int stroka;
    Queue* list = (Queue*)malloc(sizeof(Queue));
    // 初始化Queue的head和tail为NULL
    list->head = NULL;
    list->tail = NULL;

    // 先读取第一个字符,避免未初始化判断
    stroka = getchar();
    while(stroka != EOF) {
        input(list, &stroka);
        stroka = getchar();
    }
    printf("\n");
    print(list);

    // 补充内存释放逻辑,避免泄漏
    Item* temp;
    while (list->head != NULL) {
        temp = list->head;
        list->head = list->head->next;
        free(temp);
    }
    free(list);
    return 0;
}

关键修改说明

  • 分配Queue后立即初始化head和tail为NULL,确保input中的条件判断基于有效值。
  • 调整循环逻辑:先执行一次getchar再进入循环,避免第一次判断使用未初始化的stroka。
  • 自动过滤EOF:仅当读取到的字符不是EOF时才插入队列,修正逻辑bug。
  • 补充print函数实现和内存释放代码,完善程序完整性。

内容的提问来源于stack exchange,提问作者dima fgb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:00:52