c - 使用malloc分配内存失败

标签 c

我创建了一个二维数组来模拟缓存。对于每个缓存行,我使用 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;
}

最佳答案

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

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

要以正确的方式工作,请将条件更改为:

(缓存[i]==NULL)

当 malloc 失败时,其计算结果为 TRUE

关于c - 使用malloc分配内存失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19233067/

相关文章:

c - MPI-- 生产者和消费者

c - 理解这个头文件的这一部分

c - ListView 控件中的项和子项

c - 如何清除内存中的char*数组?

c - 尝试在 C 语言中思考字符串大小

c - 将结构的大小作为 void 传递给函数

c - 与共享库链接

c - C语言中extern buffer[]和extern *buffer有什么区别?

c++ - FSM 在 C++ 中使用成员函数指针

C 全局结构 : "error: expected expression before ' {' token"