c - 缓存模拟
问题描述
我开始使用 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。谢谢。
解决方案
而不是局部变量:
int cache[cacheSize];
使用堆分配的变量:
int * cache = malloc(sizeof(int) * cacheSize);
还要确保检查分配是否成功。见malloc(3)
:
出错时,这些函数返回 NULL。
并稍后调用free(cache)
。
推荐阅读
- android - ANDROID : Gradle 传入一个参数,例如 serverURL
- amazon-dynamodb - 如何动态更新 dynamodb 项目中的属性?
- python - 如何使用脚本来控制程序的输入?
- excel - 在一个 Excel 表中创建属性值的笛卡尔积
- php - 尊重验证规则 email() 验证电子邮件地址 ne fonctionne pas
- url - 将域绑定到十月 CMS 主题文件夹
- dialogflow-es - 如何让我的聊天机器人消息在对话流中有几秒钟的延迟响应?
- javascript - 如何将 js Map 传入 Spring 控制器
- angular - 如何在 Angular 7 项目中集成 html 模板
- javascript - 从 js ajax 调用运行 python 文件,它创建一个 JSON 文件