如何在釋放動態變數之后將動態分配變數的值傳遞給只讀變數。
假設我有一個函式可以創建一個我想要的任意長度的字串,然后在下面看到的主字串中呼叫它來列印函式生成的字串,但后來我忘記釋放或者我不想釋放正如我所期望的那樣,它已經在函式中被釋放了
1 ~ │ #include <stdio.h>
2 ~ │ #include <stdlib.h>
3 ~ │ #include <string.h>
4 ~ │
5 ~ │ char *CreateTxt();
6 ~ │
7 ~ │ int main() {
8 ~ │ char *str = CreateTxt();
9 ~ │ printf(("%s\n"), str);
10 ~ │ }
11 ~ │
12 ~ │ char *CreateTxt() {
13 ~ │ char *p_dynamicTxt = calloc(5, sizeof(char));
14 ~ │ strcpy(p_dynamicTxt, "A");
15 ~ │ char *string = p_dynamicTxt;
16 ~ │ free(p_dynamicTxt); // Want to free here instead of after calling
17 ~ │ return string;
18 ~ │ }
我希望能夠釋放在函式中使用 calloc 分配的變數,以便其他可能使用該函式的人不必擔心釋放回傳值
顯然,當我編譯并運行時,我得到了這個
-- Configuring done
-- Generating done
-- Build files have been written to: /home/prxvvy/workspace/a/cmake-build-debug
[2/2] Linking C executable a
??o]
^[[?1;2c%
uj5u.com熱心網友回復:
如何在釋放動態變數之后將動態分配變數的值傳遞給只讀變數。
你不能。分配物件的生命周期在它被釋放時結束。未定義的行為是由于嘗試在其生命周期之外訪問物件而導致的。
我希望能夠釋放在函式中使用 calloc 分配的變數,以便其他可能使用該函式的人不必擔心釋放回傳值
很高興你想讓你的用戶更容易,但你提出的不是你可以做到的方法。最好的辦法是清楚地記錄呼叫函式的所有要求,例如釋放函式回傳值指向的資料。然后呼叫者有責任根據其檔案使用該函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434828.html
標籤:C
