-2

我创建了一个二维数组来模拟缓存。对于每个缓存行,我使用 struct 来定义它。当我想初始化cahce时,使用malloc时出了点问题。我在代码中标记了错误的位置。谢谢!

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;
}
4

2 回答 2

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

也可以是 malloc (0 * 4) !

你也可以用完内存。

于 2013-10-07T19:36:50.463 回答
1
if (cache[i])
    {
        printf("%s\n", "allocate memory failed  22222222");
        exit(-1);
    }

cache[i]是!= NULL 时退出,这意味着您在分配内存时退出。

要以正确的方式将条件更改为:

(cache[i]==NULL)

TRUE当 malloc 失败时,这将评估为。

于 2013-10-07T19:40:48.507 回答