qq_20906467
Stardust741953
采纳率50%
2018-04-05 06:45

引发的异常: 0xC0000005: 写入位置 0xCDCDCDCD 时发生访问冲突。

5
已采纳

#include
#include
#include

#define LEN sizeof(struct student)

struct student *creat();
void print(struct student *head);

struct student
{
int num;
float score;
struct student *next;
};

int n;

void main()
{
struct student *stu;

stu = creat();
print( stu );

printf("\n\n");
system("pause");

}

struct student *creat()
{
struct student *head;
struct student *p1, *p2;

p1 = p2 = (struct student *)malloc(LEN);

printf("please enter the num:\n");
scanf_s("%d", p1->num,sizeof(p1->num));
printf("please enter the score:\n");
scanf_s("%f", p1->score,sizeof(p1->score));

head = NULL;
n = 0;

while (p1->num)
{
    n++;
    if (n == 1)
    {
        head = p1;
    }
    else
    {
        p2->next = p1;
    }
    p2 = p1;
    p1 = (struct student *)malloc(LEN);

    printf("please enter the num:\n");
    scanf_s("%d", p1->num, sizeof(p1->num));
    printf("please enter the score:\n");
    scanf_s("%f", p1->score, sizeof(p1->score));
}
p2->next = NULL;

return head;

}

void print(struct student *head)
{
struct student *p;
p = head;
while (p->next)
{
printf("学号: %d 分数: %f\n", p->num, p->score);
p = p->next;
}
}

运行环境为vs2017,win10 64位。在运行到第一个scanf_s处是报的错:
0x0F86742E (ucrtbased.dll)处(位于 lianbiao.exe 中)引发的异常: 0xC0000005: 写入位置 0xCDCDCDCD 时发生访问冲突。

看见有人说是引用了未初始化的内存,那么怎么初始化呢?试过calloc函数,报错如下:
图片说明

求大佬教教,感激不尽!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • SecretGarden SecretGarden 3年前

    所有的scanf函数后面的变量都应该取地址,例如:
    将:

    scanf_s("%d", p1->num, sizeof(p1->num));
    

    改为:

    scanf_s("%d", &p1->num, sizeof(p1->num));
    
    点赞 2 评论 复制链接分享
  • lovefox_zoe lovefox_zoe 3年前

    stu = creat();???

    点赞 1 评论 复制链接分享

相关推荐