我不使用free()时应用程序崩溃

时间:2019-04-02 22:26:51

标签: c malloc

使用malloc()后尝试初始化变量时,应用程序崩溃。

使用free()或将错误的代码块放在其他2之上可以解决所有问题,但是为什么呢?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>

int main()
{
    LARGE_INTEGER startTime, endTime, ticksPerSecond;
    int a = 10000;
    int b = 25000;
    float *allocazione;
    QueryPerformanceFrequency(&ticksPerSecond);

    QueryPerformanceCounter(&startTime);
    allocazione = (float*)malloc(a*b*sizeof(float));
    QueryPerformanceCounter(&endTime);
    printf("Tempo di allocazione con malloc : \n%g\n", (double)(endTime.QuadPart - startTime.QuadPart)/(double)ticksPerSecond.QuadPart);

    free(allocazione); //Commenting this causes the application to crash. Why?

    QueryPerformanceCounter(&startTime);
    allocazione = (float*)calloc(a*b,sizeof(float));
    QueryPerformanceCounter(&endTime);
    printf("Tempo di allocazione con calloc : \n%g\n", (double)(endTime.QuadPart - startTime.QuadPart)/(double)ticksPerSecond.QuadPart);

    free(allocazione); //Commenting this causes the application to crashes. Why?

    //Having the piece of code on top solves all the issues. Why?
    QueryPerformanceCounter(&startTime);
    allocazione = (float*)malloc(a*b*sizeof(float));
    for(int i = 0; i < a; i++)
        for (int j = 0; j < b; j++)
        *(allocazione + i * b + j) = 0.0f; //Application crash!!!
    QueryPerformanceCounter(&endTime);
    printf("Tempo di allocazione con malloc + for loop per inizializzare : \n%g\n", (double)(endTime.QuadPart - startTime.QuadPart)/(double)ticksPerSecond.QuadPart);

    return 0;
}

1 个答案:

答案 0 :(得分:3)

每个分配用于2.5亿float秒,需要稳定的GB内存。奇怪的是,您正在构建一个32位应用程序,这意味着您只有2 GB(对于特殊OS配置可能为3 GB)的用户虚拟内存地址空间。

由于未通过free,您正在尝试分配三个1 GB的块,这不适合; malloccalloc调用之一可能失败,并且您没有检查返回值,因此甚至看不到它。当您尝试使用失败分配中的NULL返回时,就会崩溃。

相关问题