原文首发地址:C语言常见的内存错误及对策 - 知乎
1.结构体成员指针未初始化
struct student
{
char *name; //这里只是分配了4个字节,没有指向一个合法的地址,内部是一些乱码
int score;
}stu,*pstu;
int main()
{
strcpy(stu.name,"code"); //所以这里会出错,解决方法就是为name指针malloc一块空间
stu.score = 99;
return 0;
}
另一种错误
int main()
{
pstu = (struct student*)malloc(sizeof(struct student));//这里还是没分配name内存,只是以为分了而已。
strcpy(pstu->name,"code");
pstu->score = 99;
free(pstu);
return 0;
}
2.没有为结构体指针分配足够的内存
int main()
{
pstu = (struct student*)malloc(sizeof(struct student*));//这里写错了 sizeof(struct student),导致内存不足
strcpy(pstu->name,"code");
pstu->score = 99;
free(pstu);
return 0;
}