我正在努力使用以下用C语言编写的代码。它在执行时会出现分段错误。 执行行
时出错scanf("%d %d %d %d",&(plist[i]->arrival),&(plist[i]->burst),&(plist[i]->deadline),&(plist[i]->period));
以下是整个代码,它不提供编译错误但运行时错误。 如果有人在这里可以告诉我我在哪里犯错,那我会很棒。
#include <stdio.h>
#include <stdlib.h>
#define INT_MAX 9999999
struct task
{
int arrival,burst,period,deadline,remaining,flag;
};
void main()
{
int i,n,time,flags=0,smallest;
struct task *list,**plist;
printf("\nEnter number of tasks :: ");
scanf("%d",&n);
list= (struct task *)malloc(sizeof(struct task)*n+1);
plist=(struct task **)malloc(sizeof(struct task*)*n+1);
for (i=0;i<=n;++i)
{
plist[i]=&list[i];
}
plist[n]->deadline=plist[n]->remaining=plist[n]->arrival=INT_MAX;
for (i=0;i<n;++i)
{
printf("\nEnter Arrival time, Burst time, Deadline & Period of task T%d ::",i);
scanf("%d %d %d %d",&(plist[i]->arrival),&(plist[i]->burst),&(plist[i]->deadline),&(plist[i]->period));
plist[i]->flag=0;
plist[i]->remaining=plist[i]->burst;
}
for(time=0;;time++)
{
smallest=n;
for(i=0;i<n+1;++i)
{
if(plist[i]->arrival<=time &&
plist[i]->deadline<plist[smallest]->deadline &&
plist[i]->remaining>0)
{
smallest=i;
}
}
plist[smallest]->remaining--;
if(plist[smallest]->remaining==0)
{
if((plist[smallest]->flag==0))
{
plist[smallest]->arrival=0;
}
plist[smallest]->flag=1;
plist[smallest]->arrival+=plist[smallest]->period;
plist[smallest]->remaining=plist[smallest]->burst;
printf("\nTask T%d completed at time %d.",smallest,time+1);
int j;
flags=0;
for(j=0;j<n;++j)
{
flags+=plist[j]->flag;
}
}if(flags==n)break;
}
free(plist);
free(list);
system("pause");
}
答案 0 :(得分:1)
问题是,在代码中为struct和pointer数组分配了一个额外的字节
list= (struct task *)malloc(sizeof(struct task)*n+1);
plist=(struct task **)malloc(sizeof(struct task*)*n+1);
但您的[n]
索引显示您需要为每个分配一个额外的数组元素,因此您需要(n+1)
周围的括号
list= (struct task *)malloc(sizeof(struct task)*(n+1));
plist=(struct task **)malloc(sizeof(struct task*)*(n+1));