-2
我創建了二維數組來模擬緩存。對於每個緩存行,我使用struct來定義它。當我想初始化cahce時,使用malloc時出現錯誤。我在代碼中標記了錯誤的地方。 謝謝!使用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;
}
[不要轉換'malloc()']的返回值(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858) – 2013-10-07 19:36:48
'使用malloc時出錯了嗎?這是什麼東西' – exexzian
's'和'E'的值是什麼?什麼平臺? –