-2

I create a 2D array to simulator a cache. For each cache line, I use struct to define it. When i want initialize the cahce, something is wrong when using malloc. I have marked the wrong place in the code. Thanks!

typedef struct {
    int valid;
    int tag;
    int lruIndex;
} Line; 

Line** initCache(int s, int E){

    int i, j;
    //int setSize = sizeof(Line *);
    //int lineSize = sizeof(Line);
    /* allocate memory to cache */
    //printf("%d   %d\n", setSize, lineSize );
    Line** cache = NULL;
    cache = (Line **)malloc((1 << s) * sizeof(Line *)); //set 

    //check for memory error
    if (!cache)
    {
        printf("%s\n", "allocate memory failed 1111111");
        exit(-1);
    }

    for (i = 0; i < (1 << s); i++){
        cache[i] = (Line *)malloc(E * sizeof(Line));   <<<<<<< i think here something is wrong, cache[i] returns NULL and then print "allocate memory failed  22222222"

        //check for memory error
        if (cache[i])
        {
            printf("%s\n", "allocate memory failed  22222222");
            exit(-1);
        }

        for(j = 0; j < E; j++){
            cache[i][j].valid = 0;   //initial value of valid
            cache[i][j].lruIndex = j; //initial value of lruIndex 0 ~ E-1
        }
    }

    return cache;
}
Denim Datta
  • 3,740
  • 3
  • 27
  • 53
violethaze
  • 31
  • 1
  • 3

2 Answers2

1
malloc((1 << s) * sizeof(Line *)

can be malloc (0 * 4) too !

also you can run out of memory.

1
if (cache[i])
    {
        printf("%s\n", "allocate memory failed  22222222");
        exit(-1);
    }

exits when cache[i] is != NULL, what means you exit when memory is allocated.

To work correct way change condition to:

(cache[i]==NULL)

which will evaluate to TRUE, when malloc fails.

zubergu
  • 3,646
  • 3
  • 25
  • 38