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

C语言自定义Text结构体拼接两字符数组结果不符合预期

问题原因
  • 核心错误:concat函数内定义的char str[txt->length]是栈分配的局部数组,函数执行结束后该栈空间会被系统自动回收,txt->str存储的是已经失效的内存地址,后续访问属于未定义行为,值会出现异常。
  • 次要错误:拼接后的字符数组没有添加C字符串必须的结束符\0,即使内存有效,按字符串规则读取时也会读到非法内容。
  • 额外问题:原代码调用concat后没有接收返回值,也没有释放所有申请的堆内存,存在内存泄漏。
修复方案

修改核心逻辑为拼接数组使用堆内存分配,并补全字符串结束符,完整修复代码如下:

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

typedef struct _Text { 
  char *str; //指向字符串的指针
  int length; //文本长度
  int counter; //指向该结构体的文本计数
} *Text;

Text concat(Text txt1, Text txt2){
  Text txt = malloc(sizeof(*txt));
  txt->length = txt1->length + txt2->length; 
  txt->counter = 1;

  // 改为堆内存分配,多预留1字节存储字符串结束符
  char *str = malloc(txt->length + 1);
  
  for(int i=0; i < txt1->length; i++){ 
    str[i] = txt1->str[i];
  }
  
  for(int i=0; i < txt2->length; i++){ 
    str[i + txt1->length] = txt2->str[i];
  }
  // 补全字符串结束标识
  str[txt->length] = '\0';
  txt->str = str;
  return txt;
}

int main(void) {
  Text txt = malloc(sizeof(*txt));
  Text txt1 = malloc(sizeof(*txt1));
  txt->str = "hello"; txt->length = 5; txt->counter = 1;
  txt1->str = "lo"; txt1->length = 2; txt1->counter = 1;
  
  Text res = concat(txt, txt1);
  // 打印验证结果
  printf("拼接结果:%s\n", res->str);

  // 释放所有申请的堆内存,避免泄漏
  free(res->str);
  free(res);
  free(txt);
  free(txt1);
  
  return 0;
}

本次修改点如下:

  • 引入<stdlib.h>头文件,提供malloc、free的标准函数声明
  • 将局部栈数组改为堆内存分配,生命周期可跨函数使用
  • 新增字符串结束符\0的赋值逻辑,符合C字符串标准
  • 新增返回值接收、结果验证逻辑,补充堆内存释放逻辑避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:15:03