calloc会覆盖另一个变量的内存吗?

Cur*_*Cat 1 c c++ malloc calloc data-management

我正在编写一个程序,image使用对源数组(hist)中存储的数据的计算来创建灰度图像().存储在源数组中的数据在调用calloc for 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;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

-> 0.997291
-> 0
Run Code Online (Sandbox Code Playgroud)

数据会发生什么变化?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
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 8

您分配256个浮点数:

float * hist = (float *) calloc(256, sizeof(float));
Run Code Online (Sandbox Code Playgroud)

并且您可以访问第1000个元素,即UB

cout << "-> " << hist [4 * 250] << endl;
Run Code Online (Sandbox Code Playgroud)

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

要访问的第250 float元素hist,只是

cout << "-> " << hist [250] << endl;
Run Code Online (Sandbox Code Playgroud)

(因为hist是一个指针float,编译器通过乘以浮点大小来计算地址,不需要自己这样做)

如果您事先知道大小,那么静态分配数据会更好

宣言:

float hist[256]={0};
Run Code Online (Sandbox Code Playgroud)

定义时hist2img:

hist2img(float hist[256]){
Run Code Online (Sandbox Code Playgroud)

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