IDE:codeblocks 简单代码编译还是习惯用这个
头文件:stdlib.h
1.malloc和free一般成对出现。申请了内存不使用时候需要释放掉。
2.free空指针不会有任何操作。
https://segmentfault.com/q/1010000003697040
例子:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *test = NULL;
free(test);
return 0;
}
执行结果:
Process returned 0 (0x0) execution time : 0.024 s
Press any key to continue.
可以看到free空指针不会报告警,也不会执行出错。
3.malloc申请内存,会对这块内存特殊处理(加上标志位或者记录到某个表格中,这里不探究),保证只能这个内存的地址才能对其进行读写操作。所以free是去掉malloc的赋能处理的。(这里把malloc对内存的处理暂且称为赋能吧)
free后一方面系统回收了该地址,可以对改内存地址自由调度。
另一方面指针还是指向这个地址的,指针还是可以对改地址进行读写处理。只是写操作可能会引发位置错误。
例子:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *test = (int *)malloc(sizeof(int));
*test = 11;
printf("test is : %d\r\n", *test);
free(test);
printf("free test.test is : %d\r\n", *test);
*test = 1;
printf("after free, change test, test