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

C语言操作文件行时,strncpy/strstr导致程序无响应求助

问题根源与修复方案

核心问题分析

你的代码崩溃是因为内存越界访问,具体有两个关键错误:

  • malloc分配的内存不足:strlen(line)只返回字符串的有效字符长度,不包含C字符串必需的终止符\0。用这个值malloc,会导致temp没有空间存储终止符,后续操作会访问非法内存。
  • strncpy的参数错误:第三个参数用了sizeof(line)(即1024),但temp的实际大小只有strlen(line),这会强制让strncpy往temp里写入远超其容量的数据,直接触发缓冲区溢出,导致程序崩溃。

另外,strstr操作时崩溃也是因为temp没有正确的终止符,导致strstr在查找时越界访问内存。

修复后的代码

void scanLinesforArray(FILE* file, char search[], int* lineNr){
    char line[1024];
    int line_count = 0;
    while(fgets(line, sizeof(line),file) != NULL){
        ++line_count;
        printf("%d", line_count);
        printf("%s", line); // 修复:避免line含格式符导致的未定义行为
        
        // 分配内存时加1,预留终止符空间
        char *temp = malloc(strlen(line) + 1);
        if (temp == NULL) { // 新增:检查malloc是否成功,避免空指针
            perror("malloc failed");
            continue;
        }
        
        // 拷贝带终止符的完整字符串,或直接用strcpy更简洁
        strncpy(temp, line, strlen(line) + 1);
        // 替代方案:strcpy(temp, line);
        
        printf("%s\n", temp);
        free(temp);
    }
}

额外优化建议

  • 优先用strcpy替代strncpy:在确定目标缓冲区足够大的情况下,strcpy更简洁,且会自动拷贝终止符,避免手动计算长度的失误。
  • 必须检查malloc返回值:内存分配失败时malloc会返回NULL,直接操作空指针会导致崩溃,所以一定要加判断。
  • 避免直接printf(line):如果line中包含%等printf格式控制符,会触发未定义行为,建议改为printf("%s", line);。

内容的提问来源于stack exchange,提问作者seyfu-t

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:50:25