作为一项任务,我必须将两个字符串连接在一起并分配内存。完成后我希望能够free(*gluedstring)
释放分配的内存。但现在我无法理解如何解决这个问题。
int strlen(char *s);
char *create_concatenated_cstring(char *source1, char *source2);
void destroy_cstring(char **gluedstring);
int main()
{
char *string1 = "Common sense is genius ";
char *string2 = "dressed in its working clothes.";
char *together = create_concatenated_cstring(string1, string2);
printf("Aan elkaar geplakt vormen de strings de volgende " \
"quote:\n\n\"%s\"\n\n", together);
destroy_cstring(&together);
if (NULL == together)
printf("De string was inderdaad vernietigd!\n");
return 0;
}
int strlen(char *s)
{
int n = 0;
for (n = 0; *s != '\0'; s++, n++);
return n;
}
char *create_concatenated_cstring(char *source1, char *source2)
{
int size = strlen(source1) + strlen(source2) + 1;
char *source3 = (char *)malloc(sizeof(char) * size);
if(source3 == NULL)
{
printf("ERROR\n");
return 0;
}
int i=0, j=0, k;
int lengte1 = strlen(source1);
int lengte2 = strlen(source2);
for(;i<lengte1;i++)
{
*(source3 + i) = *(source1 + i);
printf("%c", *(source3+i));
}
for(j=i, k=0;k<lengte2;j++, k++)
{
*(source3 + j) = *(source2 + k);
}
return source3;
}
void destroy_cstring(char **gluedstring)
{
free(gluedstring);
}
答案 0 :(得分:5)
因为你正在释放堆栈地址。你需要取消引用指针,就像这个
free(*gluedstring);
// ^ `free' the pointer not it's address (or the pointer to it)
*gluedstring = NULL; // Prevent double `free' for example
请注意,free()
没有指针NULL
,这就是为什么传递指针地址是好的,因为您可以将它设置为NULL
并避免有悬挂的指针。