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

二维数组赋值越界?链表转字符数组逻辑错误排查求助

问题描述

正在处理链表转字符数组的逻辑:遍历链表时,以换行符(ASCII码10)作为分隔符拆分不同字符组,最终存入二维数组以便后续线性搜索。但测试时发现两个问题:

  • 明明分配的行大小cur_max不大,链表内容较多时,for循环会把链表中不断缩短的片段写入行,还经常超出分配的行大小;
  • 本该在每行末尾添加的'\0',只有最后一行生效。

补充背景:链表仅通过尾部添加元素,遍历从头部节点开始。

问题代码
// traces are just character arrays. cur max is the max length of a trace. 
char arr_all_traces[total_trace_count][cur_max];
// run through the linked list again and add to the array.
temp = current_trace.head;

for (int i = 0; i < total_trace_count; i++) {
    for (int j = 0; j <= cur_max; j++) {
        if (temp->actn == 10 || j == cur_max) { 
             arr_all_traces[i][cur_max] = '\0';
             temp = temp->next;  
             j = 0;
             break;
        }
        if (temp->actn != 10 && temp != NULL){
            arr_all_traces[i][j] = temp->actn;
            temp = temp->next;  
        }
     }
 }
问题分析与修复方案

核心问题点

  1. 数组越界严重:
    • 二维数组arr_all_traces[i]的大小是cur_max,下标范围是0~cur_max-1,但代码里直接写arr_all_traces[i][cur_max] = '\0',这会直接越界写入相邻内存,破坏其他行的数据,导致出现“不断缩短的片段”这种诡异现象。
    • 内层循环条件j <= cur_max,当j等于cur_max时,已经超出了数组的有效下标范围。
  2. 空指针检查顺序错误:
    • 代码里先判断temp->actn != 10再检查temp != NULL,如果temp已经是NULL,访问temp->actn会直接触发崩溃。
  3. 字符串终止逻辑错误:
    • 只有触发if (temp->actn ==10 || j==cur_max)时才写'\0',但这个写入位置是越界的,而且如果一行没遇到换行符也没到cur_max(比如链表提前结束),该行就没有终止符。

修复后的代码

// traces are just character arrays. cur max is the max length of a trace. 
char arr_all_traces[total_trace_count][cur_max];
// run through the linked list again and add to the array.
temp = current_trace.head;

for (int i = 0; i < total_trace_count && temp != NULL; i++) {
    int j = 0;
    // 只写到cur_max-1,留一个位置给终止符
    while (j < cur_max - 1 && temp != NULL) {
        if (temp->actn == 10) {
            // 遇到换行符,跳过该节点,终止当前行
            temp = temp->next;
            break;
        }
        // 写入当前字符,移动指针和下标
        arr_all_traces[i][j] = temp->actn;
        temp = temp->next;
        j++;
    }
    // 不管是换行还是到长度上限,都在末尾加终止符
    arr_all_traces[i][j] = '\0';
}

关键修改说明

  • 避免越界:把行内写入的上限改成cur_max-1,确保最后一个位置留给'\0',终止符直接写在j的位置(当前行的最后一个有效字符后)。
  • 修正空指针检查:每次访问temp前先判断temp != NULL,包括外层循环也加了temp != NULL的判断,防止链表提前结束时继续循环。
  • 简化逻辑:把内层for循环改成while循环,逻辑更清晰,避免j的重置混乱。
  • 强制每行加终止符:不管是遇到换行符、达到行长度上限还是链表提前结束,都会给当前行加上'\0',保证所有行都是合法的C字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:45:32