随机将segfault与malloc和fscanf混淆

时间:2018-12-08 08:39:51

标签: c segmentation-fault malloc scanf

我正在尝试编写一个缓存模拟器,并且似乎弄错了malloc和fscanf的概念,因为我一直在遇到段错误。

#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的顺序,则不会发生段错误。但是,从一开始,部分故障就一直发生。我可能做错了什么?这两部分中的变量彼此无关。

谢谢。

0 个答案:

没有答案