作为一项赋值,我必须将两个字符串连接在一起并分配内存。完成后,我希望能够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:nn"%s"nn", 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 != ' '; 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("ERRORn");
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);
}
因为您正在释放堆栈地址。你需要取消引用指针,就像这个
free(*gluedstring);
// ^ `free' the pointer not it's address (or the pointer to it)
*gluedstring = NULL; // Prevent double `free' for example
请注意,free()
不会使指针成为NULL
,这就是为什么传递指针地址很好,因为您可以将其设置为NULL
,并避免出现悬空指针。