我对 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/