c - 为什么字符串连接可能会在每个连接前加上垃圾前缀?

标签 c string memory memory-management

我对 C 还很陌生,所以如果这是相当标准的知识,我深表歉意。

我有一个像这样的函数,我将一堆 C 风格字符串附加在一起并输出:

char *example(int n, int days, int years){
    char *ret;
    if (n < 5) {
        ret = (char*)malloc(sizeof(char)*256);
        sprintf(ret, "There are %d days in %d years", days, years);
        ret = (char*)malloc(strlen(ret));
        return ret;
    }
    else {
        char *s1;
        char *s2;
        char *s3;
        s1 = example(n/2, days, years);
        s2 = example(n + 5, days, years);
        s3 = example(n--, days, years);

        int length = strlen(s1) + strlen(s2) + strlen(s3);
        ret = (char*)malloc(length);
        strcat(ret, s1);
        strcat(ret, s2);
        strcat(ret, s3);

        return ret;
       }
}

这会在每个新连接前添加一些垃圾字符。我假设我的问题出在内存管理中,但我不确定..这简单吗?我做错了什么?另外,如何才能更干净地完成此操作?

最佳答案

char *example(int n, int days, int years){
   char *ret;
   if (n < 5) {
       ret = (char*)malloc(sizeof(char)*256);
       sprintf(ret, "There are %d days in %d years", days, years);
//     ret = (char*)malloc(strlen(ret));  (DELETE THIS LINE)
       return ret;
   }
   else {
       char *s1;
       char *s2;
       char *s3;
       s1 = example(n/2, days, years);
       s2 = example(n + 5, days, years);  // WILL THIS CAUSE INFINITE RECURSION?
       s3 = example(n--, days, years);

       int length = strlen(s1) + strlen(s2) + strlen(s3) + 1; // ALLOW ROOM FOR TERMINATING '\0'
       ret = (char*)malloc(length);
       strcpy(ret, s1);  // CHANGE TO strcpy()
       strcat(ret, s2);
       strcat(ret, s3);

       return ret;
   }
}

关于c - 为什么字符串连接可能会在每个连接前加上垃圾前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3850276/

相关文章:

c - C 中两个数组元素地址之间的偏移量

c - 返回指针的函数

c - C 中带有字符串的函数的头文件

android(在 java 代码中更改字符串)

memory - 场景多的 Cocos2D 项目没有正确释放内存

c# - 为什么我的 Interop 代码会抛出 "Stack cookie instrumentation code detected a stack-based buffer overrun"异常?

c - 堆相关问题

c - 在字符串中搜索子字符串时出现段错误

arrays - 初始化从指针目标类型中丢弃 ‘const’ 限定符

c - 如何在结构数组中搜索字符串?