/*
============================================================================
Name : TestMemory.c
Author : lf
Version :
Copyright : Your copyright notice
Description : malloc和free
注意细节:
void * malloc (size_t size)
因为malloc函数并不知道用户获取到这块数据后存放什么类型的数据,所以返回一个通用指针void *.
用户可以将其转换成需要的类型的指针再使用.其实,void *可以和任何指针类型之间相互隐式转换.
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void testMemory();
typedef struct {
char *name;
int number;
} student;
int main(void) {
testMemory();
return EXIT_SUCCESS;
}
/**
* 1 malloc和free成对出现
* 2 在free(p)之后,再执行p=NULL
* 因为free(p)只是归还了p所指向的内存地址但是没有改变p的值,即p现在所指向的内存
* 已经不属于本用户了即p成为了野指针,所以为了避免这种情况再手动执行p=NULL
* 3 要先用malloc给给stu->name分配空间再执行strcpy
* 否则可能覆盖name指向的地址的数据造成段错误
* 4 要先释放stu->name再释放stu,否则造成stu->name
* 变成野指针无法回收其指向的内存
*/
void testMemory() {
student *stu = malloc(sizeof(student));
if (stu == NULL) {
printf("OOM\n");
exit(1);
}
stu->number = 9527;
stu->name = malloc(20);//
strcpy(stu->name, "xiao ming");
printf("stu->number=%d,stu->name=%s\n", stu->number, stu->name);
free(stu->name);
free(stu);
stu=NULL;
}
原文地址:http://blog.csdn.net/lfdfhl/article/details/44004129