使用 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%gn", (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%gn", (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%gn", (double)(endTime.QuadPart - startTime.QuadPart)/(double)ticksPerSecond.QuadPart);
return 0;
}
您的每个分配都是 2.5 亿float
秒,需要稳定的千兆字节内存。很有可能,您正在构建一个 32 位应用程序,这意味着您只有 2 GB(对于特殊操作系统配置,可能是 3 GB(的用户虚拟内存地址空间。
通过 free
,您正在尝试分配三个块,每个块 1 GB,这不适合;其中一个malloc
或calloc
调用可能失败,并且您没有检查返回值,因此您甚至看不到它。当您尝试使用从失败的分配中返回的NULL
时,您将崩溃。