对于大尺寸的输入数组,C程序崩溃(Segmentation Fault)。如何在不使用static / global / malloc的情况下阻止它?

问题描述 投票:2回答:1

以下程序是使用heapsort对大量随机数进行排序。程序的输出是递归heapSort函数的总执行时间(以微秒为单位)。输入数组的大小由SIZE宏定义。

该程序适用于SIZE高达100万(1000000)。但是当我尝试使用SIZE 1000万(10000000)执行程序时,程序会生成分段错误(核心转储)。

注意:我已经尝试在Linux(128 MB)上使用ulimit -s命令增加堆栈的软硬限制。 SEGFAULT仍然存在。

请建议我对所需代码的任何更改或任何克服现有SEGFAULT疾病的方法,而不必动态声明数组或全局/静态。 / *程序实现堆排序算法* /

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

long SIZE = 10000000; // Or #define SIZE 10000000

long heapSize;

void swap(long *p, long *q)
{
    long temp = *p;
    *p = *q;
    *q = temp;
}

void heapify(long A[], long i)
{
    long left, right, index_of_max;
    left = 2*i + 1;
    right = 2*i + 2;

    if(left<heapSize && A[left]>A[i])
        index_of_max = left;
    else
        index_of_max = i;

    if(right<heapSize && A[right]>A[index_of_max])
        index_of_max = right;

    if(index_of_max != i)
    {
        swap(&A[index_of_max], &A[i]);
        heapify(A, index_of_max);
    }       
}

void buildHeap(long A[])
{
    long i;

    for(i=SIZE/2; i>=0 ; i--)
        heapify(A,i);
}

void heapSort(long A[])
{
    long i;

    buildHeap(A);

    for(i=SIZE-1 ; i>=1 ; i--)
    {
        swap(&A[i], &A[0]);
        heapSize--;
        heapify(A, 0);
    } 
}

int main()
{
    long i, A[SIZE];
    heapSize = SIZE;
    struct timespec start, end;

    srand(time(NULL));
    for(i = 0; i < SIZE; i++)
        A[i] = rand() % SIZE;

    /*printf("Unsorted Array is:-\n");
    for(i = 0; i < SIZE; i++)
        printf("%li\n", A[i]);
    */

    clock_gettime(CLOCK_MONOTONIC_RAW, &start);//start timer
    heapSort(A);
    clock_gettime(CLOCK_MONOTONIC_RAW, &end);//end timer

    //To find time taken by heapsort by calculating difference between start and stop time.
    unsigned long delta_us = (end.tv_sec - start.tv_sec) * 1000000 \
                            + (end.tv_nsec - start.tv_nsec) / 1000;

    /*printf("Sorted Array is:-\n");
    for(i = 0; i < SIZE; i++) 
        printf("%li\n", A[i]);
    */

    printf("Heapsort took %lu microseconds for sorting of %li elements\n",delta_us, SIZE);

    return 0;
}
c segmentation-fault heapsort ulimit timespec
1个回答
2
投票

因此,一旦您计划坚持使用仅限堆栈的方法,您必须了解谁是您的堆栈空间的主要消费者。

  • 播放器#1:阵列A []本身。根据操作系统/构建,它消耗大约。 40或80 Mb的堆栈。仅一次。
  • 玩家#2:小心递归!在您的情况下,这是heapify()函数。每个调用都会消耗相当大的堆栈块来提供调用约定,堆栈对齐就像堆栈帧等。如果你做了那么多次和树状模式,那么你也需要花费数十兆字节。因此,您可以尝试以非递归方式重新实现此函数以减少堆栈大小压力。
© www.soinside.com 2019 - 2024. All rights reserved.