這個問題在這里已經有了答案: free() 后出現分段錯誤,常見的原因是什么? (7 個回答) 5 小時前關閉。
我的代碼:
#include <stdio.h>
#include <stdlib.h>
int main() {
int num = 0;
printf("enter a number: ");
scanf("%d", &num);
printf("num: %d", num);
free(&num);
return 0;
}
為什么我不能釋放(釋放)保存用戶輸入的整數的記憶體?
uj5u.com熱心網友回復:
根據free(3)手冊頁:
void free(void *ptr);
The free() function frees the memory space
pointed to by ptr, which must have been
returned by a previous call to malloc(), calloc()
or realloc(). Otherwise, or if free(ptr) has
already been called before, undefined behavior
occurs. If ptr is NULL, no operation is performed.
如果您傳遞free()
了任何一個都沒有回傳的東西malloc()
,calloc()
或者realloc()
它會導致未定義的行為。
uj5u.com熱心網友回復:
函式free
需要匹配函式malloc
(或其相關函式之一,如calloc
orrealloc
或其他一些函式),一對一。每個都malloc
分配記憶體,每個都free
需要釋放之前分配的記憶體。沒有其他東西可以被釋放。
您沒有分配變數num
,因此您沒有,也不能釋放它。
變數的存盤num
稱為自動。變數在用 宣告的地方自動分配int num = 0;
。它會在函式結束時自動釋放(稱為作用域)。
請注意,許多函式會分配記憶體。
他們之中有一些是:
malloc
realloc
calloc
strdup
asprintf
vasprintf
- (特別是:不是
alloca
)
uj5u.com熱心網友回復:
因為num
沒有使用malloc
.
您不能釋放任何未使用malloc
家庭功能分配的東西。
int main(void)
{
int *num = malloc(sizeof(*num));
if(num)
{
printf("enter a number: ");
if(scanf("%d", num) == 1)
printf("num: %d", num);
}
free(num);
}
C 標準 7.20.3.2:
free 函式會導致 ptr 指向的空間被釋放,也就是說,可用于進一步分配。如果 ptr 是空指標,則不會發生任何操作。否則,如果引數與 calloc、malloc 或 realloc 函式先前回傳的指標不匹配,或者如果空間已通過呼叫 free 或 realloc 被釋放,則行為未定義
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507318.html
上一篇:如何僅使用putchar列印INT_MIN整數的最后一位?
下一篇:如何比較浮點值