случайное смешение segfault с malloc и fscanf - PullRequest
0 голосов
/ 08 декабря 2018

Я пытаюсь написать симулятор кэша, и мне кажется, что концепция malloc и fscanf ошибочна, потому что я продолжаю получать segfault.

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "getopt.h"
#include "unistd.h"

typedef struct line{
    int valid ;
    long tag ;
    long* box;
} line_t;

typedef struct set{
    int* recent;
    line_t* lines;
} set_t;

int power2(int);
int main(int argc, char *argv[])
{
    char* op;
    int addr;
    int size;
    int opt;
    int s = 0, e = 0, b = 0, verbose = 0;
    char* tracefile = "";



    while((opt = getopt(argc, argv, "vs:e:b:t:")) != -1){
        switch(opt){
            case 'v': verbose = 1;break;
            case 's': s = atoi(optarg); break;
            case 'e': e = atoi(optarg); break;
            case 'b': b = atoi(optarg); break;
            case 't': tracefile = optarg; break;
            default: break;
        }
    }



    int s_num = power2(s);
    int e_num = power2(e);
    int b_num = b;


//Part A: Malloc
    set_t* cache = malloc(sizeof(set_t) * s_num);
    for(int i = 0;i<s_num;i++){
        (cache[i]).recent = malloc(sizeof(int) * e_num);
        (cache[i]).lines = malloc(sizeof(line_t) * e_num);
        for(int j = 0;j<e_num;j++){
            (cache[i].lines[j]).box = malloc(sizeof(long) * b_num);
        }
    }


//Part B: File open
    FILE* filepoint;
    filepoint = fopen ("traces/yi2.trace", "r");
    if (filepoint == NULL) {perror("Error: file not valid"); return (-1);}

    while(fscanf(filepoint, " %s%x, %d",op, &addr, &size) == 3){
     printf("%s, %x, %d\n", op, addr, size);
    };
    fclose(filepoint);

    free(cache);
    return 0;
}

Раздражает то, что, если я меняю порядок A и B, segfault НЕ происходит.Тем не менее, в то время как часть продолжается, идет к ошибке в самом начале.Что я могу делать не так?Переменные в обеих частях не имеют ничего общего друг с другом.

Заранее спасибо.

...