【发布时间】:2019-09-16 08:15:27
【问题描述】:
我是 C 语言的新手,我正在尝试使用 Malloc 动态分配内存,然后使用“free”释放内存。
我曾尝试在 google 上搜索,但由于我刚开始学习它,到目前为止它没有任何意义。
#include <stdio.h>
#include <stdlib.h>
int main (){
printf("Enter your name:");
//Here I allocate enough memory for the "sir" array.
//allocate memory
char *sir = (char*) malloc (100 * sizeof(char));
//scan string. I am scanning a name e.g.: John Smith
scanf("%[^\n]", sir);
//size of sir
int size = strlen(sir);
printf("String size with strlen = %d\n", size);
//printing the string
for(int i = 0; i < size; i++){
printf(" %d = [%c] ", i ,sir[i]);
}
//Printing J o h n _ S m i t h
//Here I release the memory allocated
//release memory
free(sir);
//print the string after releasing memory
printf("\n\n");
for(int i = 0; i < size; i++){
printf(" %d = [%c] ", i ,sir[i]);
}
//Printing _ _ _ _ _ S m i t h
//After the above loop, I still have some input as well as some memory which I can access.
// I do not understand why free does not release whole memory.
return 0;
}
我希望在 free(sir) 行之后,我尝试访问的内存为空/不可访问。
我理解错了吗?
提前谢谢你。
【问题讨论】:
-
当你卖掉你的房子搬出去的时候,你不一定要清理它。
-
它确实会释放内存,因此它可能(或可能不会)随时被重用。它不会清除内容,因为这是 C 不需要的开销。访问空闲内存会产生不可预测的行为,因此在您的情况下会发生这种情况,在其他人的情况下使用相同的代码可能会以完全不同的方式中断。
-
你理解错了,是的。您的期望并不是一个不合理的期望,但事实证明,对于 O/S 来说,实际上使现在释放的内存不可访问的成本太高了,所以它只是被标记为空闲的。现在您不再拥有它,它可能还有其他细微的变化,但默认情况下它不会被限制。
-
建设性评论,但免费不毁我家?
-
freed 是 所有权,而不是内存,它可能仍可访问,也可能无法访问。