简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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