简体   繁体   English

为什么我不能以这种方式释放分配的内存?

[英]Why can't I free the allocated memory this way?

As an assignment I had to concatenate two strings together and allocate the memory. 作为分配,我必须将两个字符串连接在一起并分配内存。 After finishing that I expected to just be able to free(*gluedstring) to free the allocated memory. 完成后,我希望能够free(*gluedstring)释放分配的内存。 But now I can't manage how to figure it out. 但是现在我无法解决这个问题。

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);
}

Because you are freeing a stack address. 因为您要释放堆栈地址。 You need to dereference the pointer, like this 您需要像这样取消引用指针

free(*gluedstring);
//   ^ `free' the pointer not it's address (or the pointer to it)
*gluedstring = NULL; // Prevent double `free' for example

Note that free() doesn't make the pointer NULL , that's why passing the pointer address is good because you can then set it to NULL and avoid having dangling pointers. 需要注意的是free()不会使指针NULL ,这就是为什么经过指针地址是一件好事,因为你就可以将其设置为NULL ,并避免悬摆指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM