卡洛克覆盖了另一个变量的内存?

calloc overwrites another variable's memory?

本文关键字:内存 变量 另一个 洛克 覆盖      更新时间:2023-10-16

我正在编写一个程序,使用存储在源数组(hist)中的数据计算来创建灰度图像(image)。

调用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

数据发生了什么?在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;

(由于histfloat的指针,编译器通过乘以浮点数大小来计算地址,不需要自己做)

如果您提前知道大小,则最好静态分配数据

声明:

float hist[256]={0};

定义hist2img时:

hist2img(float hist[256]){

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