C语言常见的内存错误及对策
【摘要】
原文首发地址:C语言常见的内存错误及对策 - 知乎
1.结构体成员指针未初始化
struct student{ char *name; //这里只是分配了4个字节,没有指向一个合法的地址,内部是一些乱码 int score;}stu,*pstu; int main(){ strcpy(stu.name,"co...
原文首发地址: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;
-
}
文章来源: allen5g.blog.csdn.net,作者:CodeAllen2022,版权归原作者所有,如需转载,请联系作者。
原文链接:allen5g.blog.csdn.net/article/details/125075402
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)