c++ - calloc 覆盖另一个变量的内存?

标签 c++ c malloc calloc data-management

我正在编写一个程序,使用对存储在源数组 (hist) 中的数据进行计算来创建灰度图像 (​​image)。为图像调用 calloc 后,存储在源数组中的数据重置为零。

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

数据会发生什么变化? hist 中的所有元素在 calloc 指令之后均为 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 :

float * hist = (float *) calloc(256, sizeof(float));

然后您访问第 1000 个元素,即 UB

cout << "-> " << hist [4 * 250] << endl;

calloc 调用将您错误指向的一些内存归零

要访问 hist 的第 250 个浮点元素,只需

cout << "-> " << hist [250] << endl;

(因为histfloat上的指针,编译器通过乘以float大小来计算地址,不需要你自己做)

如果事先知道大小,静态分配数据就更好了

声明:

float hist[256]={0};

定义hist2img时:

hist2img(float hist[256]){

在这种情况下,当静态索引超出范围时您会收到警告(但如果某些变量索引超出范围,仍然会崩溃/UB:没有运行时检查)

关于c++ - calloc 覆盖另一个变量的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265287/

相关文章:

c# - 从 C++ 使用 COM Interop 对象

c++ - IE Explore 11 < c++ ATL COM Browser Helper Object (Add-on) 替换 DOM 中的文本

c - 何时使用 HANDLE_EINTR 或 HANDLE_EAGAIN?

c++ - 调试 C/C++ 语言不命中断点

c - C中的内存分配

c++ - 设置操作系统标志以测试操作系统特定功能

c++ - 在文件流c++中打开一个简单的函数

c - 什么时候应该将数组名称视为指针,什么时候它只代表数组本身?

C++ 函数返回 const char *

c - 输入大小未知