1.野指针
#include<string.h>structstudent{char* name;//分配结构体内存时name未初始化,极易出错int score;}stu,*pstu;int main(){pstu=(struct student*)malloc(sizeof(struct student));//隐含name野指针strcpy(stu.name,"Jimy");//野指针,出错stu.score=99;return0;}
2.按值传递
#include<stdlib.h>#include<string.h>
void GetMemory(char*p,int num)
{
//实际上只是让指针副本_str指向一块堆内存,正确做法可以用二级指针或者用返回值的方式
p=(char*)malloc(num*sizeof(char));
}
int main()
{char* str=NULL;
GetMemory(str,10);//并没有分配到内存
strcpy(str,"hello");
free(str);//free并没有起作用,内存泄漏
return0;
}
原文:http://www.cnblogs.com/encode/p/3550051.html