Reputation: 5
The application crashes when trying to initialize variables after using malloc().
Using free(), or placing the faulty block of code on top of the other 2, solves all the issues, but why?
#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;
}
Upvotes: 0
Views: 78
Reputation: 155418
Each of your allocations is for 250 million float
s, requiring a solid gigabyte of memory. Odds are, you're building a 32 bit application, and that means you only have 2 GB (maybe 3 GB for special OS config) worth of user virtual memory address space.
By failing to free
, you're trying to allocate three blocks of 1 GB a piece, which won't fit; one of the malloc
or calloc
calls are likely failing, and you're not checking the return value so you don't even see it. When you try to use the NULL
return from the failed allocation, you crash.
Upvotes: 3