[英]segfault in merge sort implementation
I'm working on a C implementation as an exercise (I'm a student). 我正在研究C实现作为练习(我是学生)。 I have the logic fine (I've used the implementation itself before), but I get a segfault when actually running it.
我的逻辑很好(我以前使用过它自己的实现),但是在实际运行时我遇到了段错误。 I've looked for a long time, and I can't understand what's causing it.
我已经找了很久,我无法理解是什么造成的。 Here is my complete code:
这是我的完整代码:
#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");
}
The output is as follows: 输出如下:
50 (this is a random number, but it always prints successfully)
Pre-Sorted Array:
Segmentation fault
So the segfault triggers when I try to loop to print the pre sorted array, but I've just proven that the array values were properly set, so I can't fathom this error. 因此,当我尝试循环打印预排序数组时,会触发段错误,但我刚刚证明数组值已正确设置,因此我无法理解此错误。 Help?
救命?
You have the following code: 您有以下代码:
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];
}
...
That code will get called, at one point, with the following arguments: 一次使用以下参数调用该代码:
list_of
is an array of 50 integers. list_of
是一个包含50个整数的数组。 buffer_of
is an array of 25 integers. buffer_of
是一个包含25个整数的数组。 start
is 0. start
是0。 end
is 50. end
是50。 You will copy 50 elements of list_of
into buffer_of
, but buffer_of
has only room for 25 elements. 您将
list_of
50个元素复制到buffer_of
,但buffer_of
只有25个元素的空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.