简体   繁体   English

在 C 中为我的进程调度模拟器程序逐行读取文件时出现分段错误(核心转储)错误

[英]Segmentation fault (core dumped) error while reading a file line by line in C for my process scheduling simulator program

I have a program that takes information about processes from a text file, and then uses the desired CPU scheduling algorithm to schedule the process and print them accordingly.我有一个程序从文本文件中获取有关进程的信息,然后使用所需的 CPU 调度算法来调度进程并相应地打印它们。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/time.h>
#include<time.h>

//Structure to store the information about a process
typedef struct{

    int pid;
    int arrival;
    int burst;

}Processes;

//Array of structure
typedef struct
{
    Processes *array;
    size_t used;
    size_t size;
} Array;

enum ALGORITHM_TYPE{FCFS, RR, SRTF};                        //enum for creating the algorithm types
int procNum = 0;                                            //Variable to keep track of number of processes
Array proc, fin;


//Function to determine the number of processes
void procNumFunction(char *fileName){

    FILE *fp;                                               //File pointer
    char *buffer, c;

    fp = fopen(fileName, "r");
    if(fp == NULL)
        exit(1);

    // Extract characters from file and store in character c
    for (c = getc(fp); c != EOF; c = getc(fp))
        if (c == '\n') // Increment count if this character is newline
            procNum++;

    printf("\nTotal %d tasks are read from \"%s\"\n\n", procNum, fileName);

}

//function to dynamically fill the array
void initArray(Array *a, size_t initialSize)
{
    // Allocate initial space
    a->array = (Processes *)calloc(initialSize, sizeof(Processes));

    a->used = 0;                                            // no elements used
    a->size = initialSize;                                  // available nr of elements
}

// Add element to array
void insertArray(Array *a, Processes element)
{

    if (a->used == a->size)
    {
        a->size *= 2;
        a->array = (Processes *)realloc(a->array, a->size * sizeof(Processes));
    }

    a->array[a->used].pid=element.pid;
    a->array[a->used].arrival=element.arrival;
    a->array[a->used].burst=element.burst;
    a->used++;

}

//Functino to free array
void freeArray(Array *a)
{

    free(a->array);
    a->array = NULL;
    a->used = 0;
    a->size = 0;

}

//Function to read from the file
void readFile(char *fileName){

    FILE *fp = NULL;                                               //File pointer
    char *buffer = NULL, *pid = NULL, *arr = NULL, *bur = NULL,*p = NULL;
    Processes temp;
    int count = 0;

    fp = fopen(fileName, "r");
    if(fp == NULL)
        exit(1);

    //Loop to read the file line by line
    while(fgets(buffer, sizeof(buffer), fp)){

/*        copyToken(pid, buffer, sizeof(pid), "\t");
        copyToken(arr, buffer, sizeof(arr), "\t");
        copyToken(bur, buffer, sizeof(bur), "\n");*/

        while (*p) {

            if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {

                // Found a number
                long val = strtol(p, &p, 10); // Read number
                if(count == 0){

                    temp.pid = val;
                    count++;

                }
                else if(count == 1){

                    temp.arrival = val;
                    count++;

                }
                else if(count == 3){

                    temp.burst = val;
                    count++;

                }
            } else {

                p++;
            }
        }

        //Insert element into array
        insertArray(&proc, temp);
        count = 0;

    }
    fclose(fp);

}

/*void copyToken(char * dest, char *source, int len, char const *delim){

    char *token = strtok(source, delim);
    if(token != NULL){

        dest[0] = '\0';
        strncat(dest, token, len-1);

    }

}*/

void fcfs(char *fileName){

    int finCount = 0, sysTime = 0;

    //Calling this function to determine the number of processes
    procNumFunction(fileName);

    //Initializing the array
    initArray(&proc, procNum);
    initArray(&fin, procNum);

    //Reading the file
    readFile(fileName);

    while(finCount <= procNum){

        printf("<system time\t%d> process %d is running\n", sysTime, proc.array[finCount].pid);
        sysTime++;
        if(proc.array[finCount].burst != 0)
            proc.array[finCount].burst--;
        else{

            printf("<system time\t%d> process %d is finished...\n", sysTime, proc.array[finCount].pid);
            finCount++;

        }

    }

    if(finCount > procNum){

        printf("<system time\t%d> All processes finished\n", sysTime);
        printf("==================================================================================\n");

    }

}

void srtf(char * fileName){



}

//The main function of the program
int main(int argc, char *argv[]){

    //Conditions to check if the arguments have been given correctly or not
    if (argc < 2)
        printf("Error. File name missing !!!");
    else if(argc == 2)
        printf("Error. Scheduling type missing !!!");
    else{

        if(!(strcmp(argv[2],"FCFS"))){

            printf("Scheduling algorithm: %s", argv[2]);
            fcfs(argv[1]);                                  //call FCFS

        }
        else if(!(strcmp(argv[2], "RR"))){

            printf("Scheduling algorithm: %s\n", argv[2]);
            if(argc != 4)
                printf("Error. Time quantum not given !!!");
            else{

                //check if valid input

            }

        }
        else if(!(strcmp(argv[2], "SRTF"))){

            printf("Scheduling algorithm: %s", argv[2]);
            srtf(argv[1]);                                  //call SRTF

        }

    }

}

My code is not complete at this point, but it compiles and runs.我的代码此时还没有完成,但它可以编译并运行。 I just wanted to run the program and see if my program is working correctly for at least the FCFS algorithm.我只是想运行该程序,看看我的程序是否至少对 FCFS 算法运行正常。

I tested the program using this file named input1.txt我使用名为 input1.txt 的文件测试了该程序

1 0 10
2 0 9
3 3 5
4 7 4
5 10 6
6 10 7

Here, the first numbe is the PID for the process, the second number is the Arrival time for the process and the third number is the Burst time for the process.这里,第一个数字是进程的PID,第二个数字是进程的到达时间,第三个数字是进程的突发时间。 In total, there are 6 processes.总共有6个进程。

My problem here is that when I run the program, it manages to run with the following output:我的问题是,当我运行该程序时,它设法以以下输出运行:

$ ./a.out input1.txt FCFS
Scheduling algorithm: FCFS
Total 5 tasks are read from "input1.txt"

Segmentation fault (core dumped)

What I don't understand here is that my am I getting a segmentation fault, and after running through the eclipse debugger, the program stops at the line while(fgets(buffer, sizeof(buffer), fp)){ in the readFile function.我在这里不明白的是,我遇到了分段错误,并且在通过 Eclipse 调试器运行后,程序在 readFile 函数中的while(fgets(buffer, sizeof(buffer), fp)){行停止. Can anyone help me as to what I am doing wrong because I think my implementation for reading a file line by line is correct?任何人都可以帮助我了解我做错了什么,因为我认为我逐行读取文件的实现是正确的?

Thanks in advance.提前致谢。

Your buffer is a pointer to nowhere (no space for the string allocated, ever!).您的buffer是一个指向无处的指针(永远没有分配的字符串空间!)。 It's size is the size of a pointer (4 or 8 bytes), not space for placing anything.它的大小是指针的大小(4 或 8 个字节),而不是放置任何东西的空间。 Make your buffer an array of eg 100 bytes (temporary storage!), ie char buffer[100] .使您的缓冲区成为一个数组,例如 100 字节(临时存储!),即char buffer[100]

  1. Open the file in procNumFunction() but didn't fclose() , then in readFile() you try open it again.procNumFunction()打开文件但没有打开fclose() ,然后在readFile()尝试再次打开它。

  2. procNum=0; and initArray(&proc, procNum);initArray(&proc, procNum); makes calloc(0, sizeof(Processes))使calloc(0, sizeof(Processes))
    i'm not sure what will happen on calling calloc(0), but malloc(0) is wrong here.我不确定调用 calloc(0) 会发生什么,但是 malloc(0) 在这里是错误的。 (somewhere use malloc(0) but here is not good) (某处使用 malloc(0) 但这里不好)

void *malloc(size_t size); void *malloc(size_t size);

malloc() allocates size bytes and returns a pointer to the allocated memory. malloc() 分配 size 字节并返回指向已分配内存的指针。 The memory is not cleared.记忆没有被清除。 If size is 0 , then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().如果 size 为 0 ,则 malloc() 返回 NULL 或稍后可以成功传递给 free() 的唯一指针值。

  1. after initArray , a->used is 0, a->size is 0, then insertArray()initArray之后,a->used 为 0,a->size 为 0,然后insertArray()
a->size *= 2;
a->array = (Processes *)realloc(a->array, a->size * sizeof(Processes));

make a realloc(p, 0) calling, i think it's dangerous.进行realloc(p, 0)调用,我认为这很危险。

in function: readFile() , the pointer p is initialized to NULL在函数: readFile() ,指针p被初始化为NULL

Then this statement is executed:然后执行这条语句:

while (*p) {

And since p contains NULL, the program will crash with a seg fault event.由于p包含 NULL,程序将因 seg fault 事件而崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM