您当前的位置: 首页 >  c语言
  • 4浏览

    0关注

    880博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C语言常见的内存错误及对策

CodeAllen嵌入式编程 发布时间:2022-05-31 23:27:58 ,浏览量:4

原文首发地址: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;
}
关注
打赏
1665938897
查看更多评论
立即登录/注册

微信扫码登录

0.0891s