时间排序算法的程序不断崩溃

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

我有一些代码用于时间排序算法(用于学校),但只要数组大小大于 20k,它就会崩溃。

这是我的主要文件:

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

#include "sorting.h"

#define ARG_COUNT 1

int main(int argc, char *argv[]) {
    
    if (argc != ARG_COUNT + 1) {
        printf("Too few or too many arguments passed.\n");
        exit(1);
    }

    if (atoi(argv[1]) < 10000) {
        printf("Array lenght should be at least 10 000.");
        exit(2);
    }

    int arr_lenght = atoi(argv[1]);
    srand(time(0));

    int *arr1 = (int *)calloc(arr_lenght, arr_lenght * sizeof(int));
    for (int i = 0; i < arr_lenght; i++) {
        arr1[i] = rand() % 20;
    }

    int *arr2 = (int *)calloc(arr_lenght, arr_lenght * sizeof(int));
    for (int i = 0; i < arr_lenght; i++) {
        arr2[i] = rand() % 20;
    }

    //INSERTION SORT TIMER
    int ticks_start = clock();
    insertion_sort(arr1, arr_lenght);
    int ticks_finish = clock();

    float net_ticks = ticks_finish - ticks_start;
    printf("insertion sort time:");
    printf("%fl\n", (double)net_ticks / CLOCKS_PER_SEC);
    
    //MERGE SORT TIMER
    ticks_start = clock();
    merge_sort(arr2, 0, arr_lenght - 1);
    ticks_finish = clock();

    net_ticks = ticks_finish - ticks_start;
    printf("merge sort time:");
    printf("%fl\n", (double)net_ticks / CLOCKS_PER_SEC);

    //free
    free(arr1);
    free(arr2);

    return 0;
}

main
函数旨在接受数组大小作为命令行参数,并用伪随机值填充该大小的 2 个数组,然后使用合并排序对一个进行排序,对插入排序对一个进行排序并比较时间。

c sorting clock timing time.h
1个回答
4
投票

您正在分配过多的内存。

calloc(length, length * sizeof (int))
分配
length * length * sizeof (int)
字节。您可能会将其与典型的
malloc
malloc(length * sizeof (int))
模式混淆。

假设一个4字节

int
,长度为20000,每次分配占用1.6GB内存

如果

calloc
分配内存失败,它将返回
NULL
。当这种情况发生时,一些实现(例如,POSIX)会将
errno
设置为
ENOMEM

您应该始终测试可能失败的库函数的返回值。

int *arr1 = calloc(length, sizeof *arr1);

if (!arr1) {
    perror("calloc");
    exit(EXIT_FAILURE);
}
© www.soinside.com 2019 - 2024. All rights reserved.