You need to enable JavaScript to run this app. C排序算法代码在Windows CMD中随机中断 其他平台运行正常
优惠活动
大模型
产品
解决方案
定价
更多

C排序算法代码在Windows CMD中随机中断 其他平台运行正常

main.c 随机中断问题定位

运行现象

  • 程序在Repl.it、OnlineGDB、Mimir在线平台、VSCode开发环境中均可正常运行
  • 仅在本机Windows命令提示符(CMD)环境下运行时出现随机中断:有时仅输出2行结果,有时可运行至处理40000个元素的阶段,极少能完整跑完所有流程,每次中断位置不固定
  • 初始判断为CMD或本地编译器存在运行限制

已开展的排查动作

  • 在main函数的return 0;语句前添加system("PAUSE");,问题未解决
  • 将同一份代码发送给同学Jon,在他的CMD环境下运行无异常,可确认问题仅存在于本人电脑环境
  • 按照《C语言入门》课程指引重装MinGW,问题未改善
  • 设备配置为i9处理器、16GB内存,可排除硬件性能限制因素
  • 搭配leak_detector_c.c运行代码,无内存泄漏相关输出,问题依旧
  • 留存3张运行异常状态的CMD输出截图

根因定位

程序存在未定义的数组越界访问,是导致随机崩溃的核心原因:

  1. 数组边界参数传递错误
    程序中整型数组的合法可访问最大下标为数组长度-1,但主函数中调用归并排序、快速排序时,传入的右边界参数直接使用了数组长度值:
  • mergeSort(sortedArray, 0, sizes[i]);
  • quickSort(sortedArray, 0, sizes[i]);
    上述调用会让排序函数访问到数组存储空间之外的内存地址,触发未定义行为。这类行为在不同环境下的表现完全随机:部分环境下越界访问的内存未受系统保护,程序可正常运行;本机运行环境下,越界访问会触发内存访问异常,导致程序随机中断,且中断位置受随机数生成逻辑影响无固定规律。
  1. 代码不规范写法放大运行时不稳定性
  • 随机数生成函数的循环初始化误写为for(i=0l; i<size; i++),将数字0写为长整型字面量0L,虽不直接触发崩溃,但属于不规范写法
  • 冒泡排序中的交换函数调用写为swap(&A[j], &A[j]+1);,虽语法上等价于正确写法,但可读性差,极易在后续修改时引发越界问题

修正方案

将主函数中两个排序函数的调用参数修改为正确的数组边界值:

  • 把mergeSort(sortedArray, 0, sizes[i]); 替换为 mergeSort(sortedArray, 0, sizes[i] - 1);
  • 把quickSort(sortedArray, 0, sizes[i]); 替换为 quickSort(sortedArray, 0, sizes[i] - 1);

附完整main.c代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAXVAL 100000

void randArray(int A[], int size, int maxval)
{
    int i;

    for(i=0l; i<size; i++)
        A[i] = rand()%maxval + 1;
}

void arrayCopy(int from[], int to[], int size)
{
    int j;
    for(j=0; j<size; j++)
        to[j] = from[j];
}

long timediff(clock_t t1, clock_t t2)
{
    long elapsed;
    elapsed = ((double)t2-t1) / CLOCKS_PER_SEC * 1000;
    return elapsed;
}

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void bubbleSort(int A[], int n)
{
    int i, j;

    for(i=n-2; i>=0; i--)
    {
        for(j=0; j<=i; j++)
            if(A[j] > A[j+1])
                swap(&A[j], &A[j]+1);
    }
}

void insertionSort(int arr[], int n)
{
    int i, item, j;
    for (i = 1; i < n; i++)
    {
         item = arr[i];

        /* Move elements of arr[0..i-1], that are
          greater than key, to one position ahead
          of their current position */
          for(j=i-1; j>=0; j--)
          {
              if(arr[j]>item)
                arr[j+1] = arr[j];
              else
                break;

          }
          arr[j+1] = item;
    }
}

void merge(int arr[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 =  r - m;

    /* create temp arrays */
    int *L = (int*) malloc(n1*sizeof(int));
    int *R = (int*) malloc(n2*sizeof(int));

    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1+ j];

    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < n1 && j < n2)
    {
        if (L[i] <= R[j])
        {
            arr[k] = L[i];
            i++;
        }
        else
        {
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    /* Copy the remaining elements of L[], if there
       are any */
    while (i < n1)
    {
        arr[k] = L[i];
        i++;
        k++;
    }

    /* Copy the remaining elements of R[], if there
       are any */
    while (j < n2)
    {
        arr[k] = R[j];
        j++;
        k++;
    }
    free(L);
    free(R);
}

void mergeSort(int arr[], int l, int r)
{
    if (l < r)
    {
        // get the mid point
        int m = (l+r)/2;

        // Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

       // printf("Testing l=%d r=%d m=%d\n", l, r, m);

        merge(arr, l, m, r);
    }
}

int partition(int *vals, int low, int high)
{
  // Pick a random partition element and swap it into index low.
  int i = low + rand()%(high-low+1);
  swap(&vals[low], &vals[i]);

  int lowpos = low; //here is our pivot located.

  low++; //our starting point is after the pivot.

// Run the partition so long as the low and high counters don't cross.
  while(low<=high)
  {
    // Move the low pointer until we find a value too large for this side.
    while(low<=high && vals[low]<=vals[lowpos]) low++;

    // Move the high pointer until we find a value too small for this side.
    while(high>=low && vals[high] > vals[lowpos]) high--;

    // Now that we've identified two values on the wrong side, swap them.
    if (low<high)
     swap(&vals[low], &vals[high]);
  }

  // Swap the pivot element element into its correct location.
  swap(&vals[lowpos], &vals[high]);

  return high; //return the partition point
}

// Pre-condition: s and f are value indexes into numbers.
// Post-condition: The values in numbers will be sorted in between indexes s
//                 and f.
void quickSort(int* numbers, int low, int high) {

    // Only have to sort if we are sorting more than one number
    if (low < high) {
        int split = partition(numbers,low,high);
        quickSort(numbers,low,split-1);
        quickSort(numbers,split+1,high);
    }
}

void selectionSort(int arr[], int n)
{
    int i, j, min_idx, temp;
    // One by one move boundary of unsorted subarray
    for (i = 0; i < n-1; i++)
    {
        //printf("\nIteration# %d\n",i+1);
        // Find the minimum element in unsorted array
        min_idx = i;
        for (j = i+1; j < n; j++)
        if (arr[j] < arr[min_idx])
            min_idx = j;
        // Swap the found minimum element with the first element
        temp = arr[i];
        arr[i] = arr[min_idx];
        arr[min_idx] = temp;

    }
}

int main()
{

    int sizes[] = {1000, 10000, 20000, 40000, 50000, 100000, 1000000};

    int *originalArray;

    int* sortedArray;
    int i, j;
    long elapsed;
    clock_t start, end;

    for(i=0; i<7; i++)
    {
        originalArray = malloc(sizeof(int)*sizes[i]);
        sortedArray = malloc(sizeof(int)*sizes[i]);

        randArray(originalArray, sizes[i], MAXVAL);

        arrayCopy(originalArray, sortedArray, sizes[i]);

        start = clock();
        bubbleSort(sortedArray, sizes[i]);
        end= clock();
        elapsed=timediff(start,end);
        printf("Sorting %d values took %ld milliseconds for Bubble sort.\n", sizes[i], elapsed);

        arrayCopy(originalArray, sortedArray, sizes[i]);

        start = clock();
        insertionSort(sortedArray, sizes[i]);
        end= clock();
        elapsed=timediff(start, end);
        printf("Sorting %d values took %ld milliseconds for Insertion sort.\n", sizes[i], elapsed);

        arrayCopy(originalArray, sortedArray, sizes[i]);

        start = clock();
        mergeSort(sortedArray, 0, sizes[i]);
        end = clock();
        elapsed=timediff(start, end);
        printf("Sorting %d values took %ld milliseconds for Merge sort.\n", sizes[i], elapsed);

        arrayCopy(originalArray, sortedArray, sizes[i]);

        start = clock();
        selectionSort(sortedArray, sizes[i]);
        end = clock();
        elapsed=timediff(start, end);
        printf("Sorting %d values took %ld milliseconds for Selection sort.\n", sizes[i], elapsed);

        arrayCopy(originalArray, sortedArray, sizes[i]);

        start = clock();
        quickSort(sortedArray, 0, sizes[i]);
        end = clock();
        elapsed=timediff(start, end);
        printf("Sorting %d values took %ld milliseconds for Quick sort.\n", sizes[i], elapsed);

        free(sortedArray);
        free(originalArray);
    }
    
    return 0;
}

内容的提问来源于stack exchange,提问作者andrewmccarty27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.29 12:45:05