我目前正在编写一个Burrows-Wheeler变换的实现,它需要对一个(大)数组进行排序。由于我想对递归排序函数的部分代码进行并行化处理,因此我决定在堆中分配一些局部变量(使用malloc()
)以防止堆栈溢出或 - 至少使程序正常死亡。这引发了一大堆问题。我将代码分解为基本部分(即导致问题的原因)。Malloc在递归函数中崩溃
以下代码无错地编译。使用icc编译时,生成的程序工作正常,但在使用gcc或tcc编译时会崩溃(随机)。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
unsigned char *block;
int *indexes, *indexes_copy;
void radixsort(int from, int to, int step)
{
int *occurrences, *first_index_of, i;
if((occurrences = malloc(1024)) == 0)
exit(1);
if((first_index_of = malloc(1024)) == 0)
exit(1);
memset(occurrences, 0, 1024);
for(i = from; i < to; i++)
occurrences[block[indexes[i] + step]]++;
first_index_of[0] = from;
for(i = 0; i < 256; i++)
first_index_of[i + 1] = first_index_of[i] + occurrences[i];
memset(occurrences, 0, 1024);
memcpy(&indexes_copy[from], &indexes[from], 4 * (to - from));
for(i = from; i < to; i++)
indexes[first_index_of[block[indexes_copy[i] + step]] + occurrences[block[indexes_copy[i] + step]]++] = indexes_copy[i];
for(i = 0; i < 256; i++)
if(occurrences[i] > 1)
radixsort(first_index_of[i], first_index_of[i] + occurrences[i], step + 1);
free(occurrences);
free(first_index_of);
}
int main(int argument_count, char *arguments[])
{
int block_length, i;
FILE *input_file = fopen(arguments[1], "rb");
fseek(input_file, 0, SEEK_END);
block_length = ftell(input_file);
rewind(input_file);
block = malloc(block_length);
indexes = malloc(4 * block_length);
indexes_copy = malloc(4 * block_length);
fread(block, 1, block_length, input_file);
for(i = 0; i < block_length; i++)
indexes[i] = i;
radixsort(0, block_length, 0);
exit(0);
}
即使当输入是一个非常小的文本文件(大约50个字节),则程序是非常不稳定与后两者编译器。它以〜50%的概率工作。在其他情况下,当调用malloc()
时,它在基数的第二次或第三次迭代中崩溃。它总是当输入文件更大时(约1 MiB)崩溃。在第2次或第3次迭代中...
手动增加堆没有任何好处。无论哪种方式,它不应该。如果malloc()
不能分配内存,它应该返回一个NULL
指针(而不是崩溃)。
从堆切换回堆栈使得程序可以与任一编译器一起工作(只要输入文件足够小)。
那么,我错过了什么/做错了什么?
也请在malloc()调用之后检查*** NULL指针***,绝对***不是0 ***。 –
@wildplasser:我怎么错过了?用'for(i = 0; i <255; i ++)',一切都按原样运行。 – Dennis
@Pete Wilson:我很困惑。他们不一样吗? – Dennis