我正在为FCFS调度算法编写C程序。我一直在尝试动态分配一个数组,该数组包含另一个静态整数数组中存储的进程ID。
这是我的代码:
int pid[number_of_processes]; // Stores IDs of all processes
//Storing IDs of all Processes
for(i = 1; i < n; i+=4){
pid[i] = numberArray[i];
printf("PID %d\n", pid[i]);
}
int *ptr;
ptr = (int *)malloc(number_of_processes * sizeof(int));
for(int i =0; i< number_of_processes; i++){
ptr[i] = pid[i];
printf("PTR of %d is %d\n",i,ptr[i]);
}
pid []中的值为{4,1,2,3,5} | |进程数= 5
我得到的输出是:
PTR of 0 is -395230048
PTR of 1 is 4
PTR of 2 is 100
PTR of 3 is 15
PTR of 4 is 5
预期输出是
PTR of 0 is 4
PTR of 1 is 1
PTR of 2 is 2
PTR of 3 is 3
PTR of 4 is 5
进程数= 5
int pid[number_of_processes];
如果n
足够大,并且您要向[i]添加+4
,那么您将越界,导致未定义的行为
for(i = 1; i < n; i+=4){
pid[i] = numberArray[i]; <--- stepping out of bound. Undefined behavior
}
但是,如果将n
初始化为小于5的值,那么您仅初始化了pid
数组的一个值,其他则包含了可能在打印中看到的垃圾。