0

我正在将 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

因此,当我尝试循环打印预排序数组时会触发段错误,但我刚刚证明数组值已正确设置,所以我无法理解这个错误。帮助?

4

1 回答 1

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_ofinto的 50 个元素buffer_of,但buffer_of只有 25 个元素的空间。

于 2013-11-04T04:11:00.527 回答