我有以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#elif defined __unix__
#include <unistd.h>
#endif
#define BENCH
#ifndef BENCH
#define N 10000
#endif
int main(void)
{
#ifdef BENCH
FILE* output = fopen("out.csv","w");
for (int N = 10000; N <= 100000; N += 10000)
#endif
{
int* a = malloc(N * sizeof(int));
if (a == NULL)
abort();
for (int i = 2; i < N; i++)
a[i] = 1;
#ifdef BENCH
clock_t begin = clock();
#endif
for (int i = 2; i < N; i++)
{
if (a[i])
{
#if defined (BENCH) && defined (_WIN32)
Sleep(1);
#elif defined (BENCH) && defined (__unix__)
sleep(0.001);
#endif
for (int j = i; j <= N / i; j++)
a[i * j] = 0;
}
}
#ifdef BENCH
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
fprintf(output,"%d,%f\n",N,time_spent);
free(a); //This is where the corruption occurs
#else
for (int i = 2; i < N; i++)
{
if (a[i])
printf("%9d ",i);
}
puts("");
#endif
}
#ifdef BENCH
fclose(output);
#endif
}
如果未定义BENCH
,程序将使用预定义的N并将结果显示在控制台上。该算法的性能尚未得到评估。
如果定义了BENCH
,则使用(N)
循环创建具有不同输入大小for
的多个问题实例。一旦出现问题,该算法的性能就会记录在output.csv
文件中。然后,必须释放为该实例的数组分配的内存。
至少根据microsoft Visual C ++编译器在Visual Studio 2019上所说的,这就是堆损坏发生的地方。有人知道为什么会这样吗? malloc()
和free()
在我看来都是正确的。如果删除free()
,程序运行正常。