簡體   English   中英

釋放由 function 分配的 char*

[英]Free a char* that was malloc'd by a function

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* mkstr(char str1[], char str2[])
{
        char* out = malloc(sizeof(*str1) + sizeof(*str2) + 1);
        strcpy(out, str1);
        strcat(out, str2);

        return out;
}

int main()
{
        char* str = mkstr("i use ","arch btw");
        printf("%s\n",str);
}

main()調用mkstr()時, mkstr()out調用char* 我怎樣才能從這段代碼中正確地free(out) 我可以保留它,還是操作系統會釋放 malloc 的空間?

這是最好的方法,還是有更好的方法?

我在 Linux 上(如果相關的話)。

sizeof(*x)是平台上指針的大小。 在 32 位平台上通常為 4,在 64 位平台上通常為 8。

要獲取字符串的長度,您需要使用strlen function。

更正的代碼:

char* mkstr(char str1[], char str2[])
{
        // you need to use strlen to get the length of a string
        char* out = malloc(strlen(str1) + strlen(str2) + 1);

        strcpy(out, str1);
        strcat(out, str2);
        return out;
}

int main()
{
        char* str = mkstr("i use ","arch btw");
        printf("%s\n",str);
        free(str);           // simply free str
}

理論:

在退出應用程序之前,應該釋放每個分配 object 的堆(大多數現代操作系統都會管理堆分配,即使您在退出應用程序時沒有釋放它們)。 順便說一句,釋放堆資源是一個很好的做法。

您的代碼中的問題:

  1. mkstr function 的參數應該是(const char *str1, const char *str2)而不是(char str[], char str2[])
  2. 使用calloc代替malloc以獲得更好的安全性。
  3. 使用strlen function 來確定字符串的長度,而不是sizeof
  4. void(int argc, char const **argv)設置為main function 的參數。

現在`free`堆分配:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *mkstr(const char *str1, const char *str2)
{
    char *out = calloc(sizeof(char) * (strlen(str1) + strlen(str2) + 1), sizeof(char));
    strcpy(out, str1);
    strcat(out, str2);
    return out;
}

int main(int argc, char const **argv)
{
    char *str = mkstr("i use ", "arch btw");
    printf("%s\n", str);
    free(str); // freed the heap allocated resource before exiting
    return 0;
}

無論如何,在閱讀了所有答案之后,這是新代碼。

char* mkstr(char str1[], char str2[])
{
        char* out = malloc(strlen(str1) + strlen(str2) + 1);
        strcpy(out, str1);
        strcat(out, str2);

        return out;
}

int main()
{
        char* str = mkstr("i use ","arch btw");
        printf("%s\n",str);
        free(str);

        return 0;
}

暫無
暫無

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

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