簡體   English   中英

為什么我不能以這種方式釋放分配的內存?

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

作為分配,我必須將兩個字符串連接在一起並分配內存。 完成后,我希望能夠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);
}

因為您要釋放堆棧地址。 您需要像這樣取消引用指針

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

需要注意的是free()不會使指針NULL ,這就是為什么經過指針地址是一件好事,因為你就可以將其設置為NULL ,並避免懸擺指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM