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

#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个回答

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

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

改为:

scanf_s("%d", &p1->num, sizeof(p1->num));
qq_20906467
Stardust741953 是我智障了····
2 年多之前 回复

stu = creat();???

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐