作为一项任务,我必须将两个字符串连接在一起并分配内存.完成后我希望能够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
Iharob Al As.. 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
并避免有悬空指针.
1> Iharob Al As..:因为你正在释放堆栈地址.您需要取消引用指针,就像这样
free(*gluedstring); // ^ `free' the pointer not it's address (or the pointer to it) *gluedstring = NULL; // Prevent double `free' for example注意,
free()
没有指针NULL
,这就是为什么传递指针地址是好的,因为你可以设置它NULL
并避免有悬空指针.