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

C语言将char[]字符逐位复制到char**时出现Segmentation fault报错

问题根因与修复方案

核心错误点

  • 分片总数计算错误,少分配了最后一个分片的内存
    你当前仅用chunks = size / 16计算分片数,若文本长度不是16的整数倍,剩余的不足16个字符仍需要1个独立分片存储,最终访问未分配的screen[row]指针触发段错误,你遇到的row=35时报错就是这个原因。
  • 单分片内存分配不足
    每个分片最多存储16个有效字符,还需要额外1字节存储字符串终止符\0,你仅分配16字节,当写入\0时会发生缓冲区溢出,破坏内存结构。
  • 结束判断逻辑失效
    for循环条件为i < size,i == size的分支永远不会触发,最后一个分片无法正确追加终止符。
  • 缺少头文件引用
    malloc函数依赖stdlib.h头文件,未引入会导致隐式声明问题,在部分编译环境下也会触发异常。

修复后可运行代码

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

int main() {
    char simpleText[] = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
    int size = strlen(simpleText);
    // 修正分片数计算,有余数时额外加1个分片
    int chunks = size / 16 + (size % 16 != 0 ? 1 : 0);
    char** screen = (char**) malloc(chunks * sizeof(char*));

    for (int i = 0; i < chunks; i++) {
        // 修正单分片大小,多分配1字节存终止符
        screen[i] = (char*) malloc (17 * sizeof(char));
    }

    int counter = 0;
    int row = 0; 

    for (int i = 0; i < size; i++) {
        char c = simpleText[i];
        screen[row][counter] = c;
        counter++;

        if (counter == 16) {
            screen[row][counter] = '\0';
            counter = 0;
            row++;
        }
    }
    // 补充最后一个不足16字符的分片的终止符
    if (counter > 0) {
        screen[row][counter] = '\0';
    }

    // 测试输出所有分片验证
    for (int i = 0; i < chunks; i++) {
        printf("分片%d: %s\n", i+1, screen[i]);
        free(screen[i]); // 释放内存避免泄漏
    }
    free(screen);
    printf("=========================================================\n");
    return 0;
}

额外优化建议

  • 所有malloc申请的内存使用完后要主动free,避免内存泄漏,修复代码中已补充相关逻辑。
  • 可以增加malloc返回值的空指针判断,避免内存申请失败时访问空指针触发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:24:07