我正在做一个C实现作为练习(我是一名学生)。我的逻辑很好(我以前使用过它自己的实现),但是在实际运行时我遇到了段错误。我已经找了很久,我无法理解是什么造成的。这是我的完整代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAY_CAPACITY 50
void do_sort(int* list);
void merge_sort(int* list_of, int* buffer_of, int start, int end);
void do_sort(int* list)
{
int capacity = ((ARRAY_CAPACITY) / 2);
int buffer[capacity];
merge_sort(list, buffer, 0, ARRAY_CAPACITY);
}
void merge_sort(int* list_of, int* buffer_of, int start, int end)
{
printf("%s", "hi!");
int i, t;
if((end - start) < 2) return;
int mid = (start + end) / 2;
merge_sort(list_of, buffer_of, start, mid);
merge_sort(list_of, buffer_of, mid, end);
int left = 0;
int right = mid;
for(i = 0; i < ARRAY_CAPACITY; i++)
{
buffer_of[i] = list_of[i];
}
for(t = start; t < end; t++)
{
if((left < (mid - start)) && (right == end || buffer_of[left] < list_of[right]))
{
list_of[t] = buffer_of[left];
left++;
}
else
{
list_of[t] = list_of[right];
right++;
}
}
}
int main()
{
srand(time(NULL));
int number_array[ARRAY_CAPACITY];
int i;
for(i = 0; i < ARRAY_CAPACITY; i++)
{
number_array[i] = (rand() % 100);
}
printf("%d\n", number_array[3]);
int j, m;
printf("%s\n", "Pre-Sorted Array: ");
for(j = 0; j < ARRAY_CAPACITY; j++)
{
printf("%d ", number_array[j]);
}
do_sort(number_array);
for(m = 0; m < ARRAY_CAPACITY; m++)
{
printf("%d ", number_array[m]);
}
printf("\n");
}
输出如下:
50 (this is a random number, but it always prints successfully)
Pre-Sorted Array:
Segmentation fault
因此,当我尝试循环打印预排序数组时会触发segfault,但我刚刚证明数组值已正确设置,因此我无法理解这个错误。帮助
答案 0 :(得分:2)
您有以下代码:
void merge_sort(int* list_of, int* buffer_of, int start, int end)
{
...
for(i = 0; i < ARRAY_CAPACITY; i++)
{
buffer_of[i] = list_of[i];
}
...
一次使用以下参数调用该代码:
list_of
是一个包含50个整数的数组。buffer_of
是一个包含25个整数的数组。start
为0。end
是50。您会将list_of
的50个元素复制到buffer_of
,但buffer_of
只能容纳25个元素。