首页 > 解决方案 > 缓存模拟

问题描述

我开始使用 C 程序来模拟缓存,但我遇到了一个令人困惑的问题。首先我有一个生成缓存的函数:

int * generateCache(int cacheSize){
  int cache[cacheSize];

  for(int cacheIndex = 0; cacheIndex < cacheSize-1; cacheIndex++){
    cache[cacheIndex] = -1;
  }
  return cache;
}

在我的主要功能中是这样的:

int main(){
  int cacheSize = 16;
  int * cache = generateCache(cacheSize);
  for(int i = 0; i < cacheSize; i++){
    printf("%d %d\n", i, cache[i]);
  }

  return 0;
}

但我的输出是这样的:

warning: address of stack memory associated with local variable 'cache' returned [-Wreturn-stack-address]
return cache;
1 warning generated.
0 -1
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1
10 -1
11 -1
12 0
13 0
14 0
15 0

谁能告诉我为什么最后 4 个索引被初始化为 0?无论我将前 12 个索引初始化为什么,都会发生这种情况;最后 4 个总是 0。谢谢。

标签: ccaching

解决方案


而不是局部变量:

int cache[cacheSize];

使用堆分配的变量:

int * cache = malloc(sizeof(int) * cacheSize);

还要确保检查分配是否成功。见malloc(3)

出错时,这些函数返回 NULL。

并稍后调用free(cache)


推荐阅读