我正在尝试将自己版本的strcat((与realloc混合。因此,我们的想法是,传递一个在main上声明的char*,并动态添加内存。
问题是我每次都会遇到分割错误。
这是我的代码,我希望有人能帮我:
main:
char* nombreCopia = "";
StrcatDynamic(&nombreCopia, argv[1]);
free(nombreCopia);
strcatDynamic:
int StrcatDynamic(char** dest, const char* src)
{
char* aux;
printf("%pn", *dest);
aux = realloc (*dest, (strlen(src) + strlen(*dest) + 1) );
if (aux == NULL)
{
perror("ERRORn");
}
else
{
*dest = aux;
}
strcat(*dest, src);
return 0;
}
不能free
或realloc
由""
生成的字符串。
简单的解决方案:
char* nombreCopia = strdup(""); // In lieu of `char* nombreCopia = "";`
我会做什么:
char* nombreCopia = NULL; // In lieu of `char* nombreCopia = "";`
( *dest ? strlen(*dest) : 0 ) // In lieu of `strlen(*dest)`