卡洛克覆盖了另一个变量的内存?
calloc overwrites another variable's memory?
我正在编写一个程序,使用存储在源数组(hist
)中的数据计算来创建灰度图像(image
)。
func1(){
float * hist = (float *) calloc(256, sizeof(float));
// operation to populate 'hist'
for...{
for...{
hist.....
}
}
hist2img(hist);
free(hist);
return 0;
}
hist2img(hist){
cout << "-> " << hist [4 * 250] << endl;
unsigned char * image = (unsigned char *) calloc(256 * 256, sizeof(unsigned char));
cout << "-> " << hist [4 * 250] << endl;
free(image);
return 0;
}
输出为:
-> 0.997291
-> 0
数据发生了什么?在callloc指令之后,hist
中的所有元素都为0。我需要将image
初始化为0。
--(~$)--> gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609
--(~$)--> uname
Linux 4.7.2-040702-generic x86_64 x86_64 x86_64 GNU/Linux
你分配了256个浮点数:
float * hist = (float *) calloc(256, sizeof(float));
,然后访问第1000个元素,也就是UB
cout << "-> " << hist [4 * 250] << endl;
callloc调用将错误指向
的内存归零。要访问hist
的第250个float元素,只需
cout << "-> " << hist [250] << endl;
(由于hist
是float
的指针,编译器通过乘以浮点数大小来计算地址,不需要自己做)
如果您提前知道大小,则最好静态分配数据
声明:
float hist[256]={0};
定义hist2img
时:
hist2img(float hist[256]){
在这种情况下,你得到一个警告,当静态索引超出范围(但仍然崩溃/UB如果一些变量索引越界:没有运行时检查)
相关文章:
- 当vector是tje全局变量时,c++中vector的内存管理
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 多个"常量引用"变量可以共享同一个内存吗?
- 为什么内存屏障依赖于变量?
- 在内存不足之前,我可以声明多少个 const 变量?
- C++具有模板成员变量的类. 和参数内存输出
- 为什么同一个变量的内存地址不同?
- 分配具有 2D 向量大小的变量的内存
- C++强制变量到一个固定的内存位置
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- C++在变量的内存地址上做什么来"deallocate"它?
- 如果不分配内存,我如何能够为变量创建和分配值?
- 为什么我无法获取 MSVS2019 / C++ 中字符或uint8_t变量的内存地址?
- 如果一个变量在它之前释放了另一个(相同的数据类型)变量,如何将其分配给内存?
- 函数,返回变量c++占用的内存位置的大小
- 为什么一个接一个声明的两个变量在内存中不相邻?
- 指向动态内存中结构中的变量时出现问题
- C++函数在endl(内存变量?
- 控制内存变量
- 使用内存变量初始化填充位结构体