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);
1

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your help, i changed cacheLine[i] to cacheArray[i]. once again this was great
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.

Comments

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

2 Comments

Thank you, this makes more sense now.
The malloc is not wrong, the way he is accessing it is wrong.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.