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

自定义C++ strcat函数异常:输出含特殊字符,请求排查解决

自定义strcat函数乱码问题的解决

问题重现

实现自定义strcat函数,将字符数组c拼接到a后返回指针,但结果出现乱码:

  • 输入:abc xyz
  • 预期输出:xyzabc
  • 实际输出:xyza@▲∩

调试观察到索引异常:

  • i=0时,destination[3] = source[0] = 'a'
  • i=1时,destination[8] = source[1] = 'b'
  • i=2时,destination[9] = source[2] = 'c'
  • 最终destination[10] = '\0'

原代码:

#include<iostream>
#include<string.h>
using namespace std;

char* mystrcat ( char * destination, const char *source){
    for (int i=0; i<strlen(source); i++) {
        destination[strlen(destination)+i] = source[i];
    }
    destination[strlen(destination)+strlen(source)]='\0';
    return destination;
}

int main() {
    char c[100];
    cin.getline(c, 99);
    char a[100];
    cin.getline(a,99);

    mystrcat(a,c);
    cout<<a;
    return 0;
}

问题根源

循环中每次调用strlen(destination)都会动态计算当前字符串长度,而每次赋值后destination的实际长度会增加,导致索引计算持续偏移:

  1. 初始destination为"xyz",strlen返回3,i=0时索引3+0=3,赋值'a'后字符串变为"xyza",长度变为4;
  2. i=1时,strlen(destination)变为4,索引4+1=5,赋值'b'后长度变为5;
  3. i=2时,strlen(destination)变为5,索引5+2=7,赋值'c'后长度变为6;
  4. 最终添加'\0'时,strlen(destination)为6,加strlen(source)的3得到索引9。

中间跳过的数组位置(如4、6)是未初始化的垃圾值,输出时就会显示为乱码。

修复代码

提前获取destination的初始长度,用固定值计算拼接起始位置,避免重复计算:

#include<iostream>
#include<string.h>
using namespace std;

char* mystrcat ( char * destination, const char *source){
    // 提前获取目标字符串初始长度,避免循环中重复计算
    size_t dest_len = strlen(destination);
    size_t src_len = strlen(source);
    
    for (size_t i=0; i<src_len; i++) {
        destination[dest_len + i] = source[i];
    }
    // 在拼接后的末尾添加结束符
    destination[dest_len + src_len] = '\0';
    return destination;
}

int main() {
    char c[100];
    cin.getline(c, 99);
    char a[100];
    cin.getline(a,99);

    mystrcat(a,c);
    cout<<a;
    return 0;
}

额外优化提示

  1. 用size_t存储长度,匹配strlen的无符号返回类型,避免类型不匹配问题;
  2. 可添加参数校验,判断destination和source是否为nullptr;
  3. 确保destination数组有足够空间容纳拼接结果,防止缓冲区溢出。

内容的提问来源于stack exchange,提问作者Lợi Nguyễn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:15:22