2

I am getting a segmentation fault in the initializeStruct function. I want a 2D Array pointer. Each 2D array index holds a struct of three types.

Here is the struct:

struct cacheLine {
    int validBit;
    int tag;
    int LRUcounter;
};

This is the Method that fails:

void initializeStruct(struct cacheLine **anyCache){
    int i, j;
    for (i=0;i<S;i++){
        for(j=0;j<E;j++){
            anyCache[i][j].validBit = 0; //I am getting a Segmentation fault
            anyCache[i][j].tag = 0;
            anyCache[i][j].LRUcounter = 0;
        }
    }
    return;
}

In the main, I use malloc to create my 2D array pointers:

int main(int argc, char** argv){
int opt;
char *t;

//looping over arguments from command line
while(-1 != (opt = getopt(argc, argv, "s:E:b:t:"))){
    //determine which argument it's processing
    switch(opt){
        case 's':
            s = atoi(optarg);
            break;
        case 'E':
            E = atoi(optarg);
            break;
        case 'b':
            b = atoi(optarg);
            break;
        case 't':
            t = optarg;
            break;
        //too many arguments
        default:
            printf("wrong argument\n");
            break;
    }
}
//create array
S = 1 << s;
B = 1 << b;

//allocate memory
struct cacheLine **cacheArray =  malloc(sizeof(struct cacheLine)*S*E);

//Initialize Structs
initializeStruct(cacheArray);
  • possible duplicate of [How do I correctly set up, access, and free a multidimensional array in C?](http://stackoverflow.com/questions/12462615/how-do-i-correctly-set-up-access-and-free-a-multidimensional-array-in-c) – Lundin Oct 11 '13 at 14:32

3 Answers3

2

The way you did you just malloc'ed the first dimension of your array. You need to malloc each of your lines:

struct cacheLine **cacheArray =  malloc(sizeof(struct cacheLine*)*S);
for(i = 0;i < S;i++) {
    cacheLine[i] = malloc(sizeof(struct cacheLine) * E);
}
Mauren
  • 1,955
  • 2
  • 18
  • 28
2

You are declaring a 2D-array, that is, an array of pointers. To that you assign a memory area.

What you expect:

array_0_0, array_0_1, ..., array_0_s
array_1_0, array_1_1, ..., array_1_s
...

What you actually declared:

array_0 -> NULL
array_1 -> NULL
...
array_n -> NULL
lots of wasted space

You can either use a 1D array with the malloc, and calculate your indices (i * E + j), or you can stick with the 2d array and instead initialize the lines individually. I would suggest using the 1d array.

Norwæ
  • 1,575
  • 8
  • 18
1

Your malloc is wrong - you want to allocate S in the first malloc then for each of those malloc E items; instead you are malloc'ing S*E and never pointing them at anything

Oliver Matthews
  • 7,497
  • 3
  • 33
  • 36