c - SIGSEGV报道使用pow()

CDT*_*CDT 1 c debugging segmentation-fault

编译器在tmp = pow(p[i],j);while时抛出一个SIGSEGV p[i]并且j是两个整数,并且p[i]是数组的有效元素p,我真的不知道为什么......

原始代码在这里:http://pastebin.com/DYhGeHxm

Who*_*aig 6

你有没有想到这个:

int i,j,p[2000], a[5000000],num,count,tmp;
Run Code Online (Sandbox Code Playgroud)

可能会把你推到非常近的地方,或者直接超过堆叠空间的边缘?那是

4 + 4 + 8000 + 20000000 + 4 + 4 + 4
Run Code Online (Sandbox Code Playgroud)

字节

即你有一个19.08兆字节的堆栈空间声明.考虑a至少动态分配.当我改为:

int *a = malloc(5000000 * sizeof(*a));
Run Code Online (Sandbox Code Playgroud)

并且重新编写代码,它使你完全超越了你所拥有的seg-fault.不幸的是,它在这个地方死了:

count = 0;
for(i = 0; i < num; i++) {
    for(j = 2; ;j++) {
        tmp = pow(p[i],j);
        if(tmp > 5000000) break;
        a[count++] = tmp; // <=== faulted here, count was 5000193
    }
}
Run Code Online (Sandbox Code Playgroud)

当达到分配的最大大小时,两个循环都应该中断a[].我做了以下.在顶部main():

static const int a_max = 5000000;
int *a = malloc(a_max*sizeof(*a));
Run Code Online (Sandbox Code Playgroud)

在循环中:

count = 0;
for(i = 0; i < num && count < a_max; i++)
{
    for(j = 2; count < a_max; j++)
    {
        tmp = pow(p[i],j);
        if(tmp > 5000000)
            break;
        a[count++] = tmp;
    }
}
Run Code Online (Sandbox Code Playgroud)

这会让你通过所有的设置.最后一件事是快速排序算法本身,它也显得破碎.我强烈建议从较小的数据大小开始调试.

祝你好运.


编辑如果你需要一个参考快速排序算法,我有一个坐在我的一个垃圾文件夹的源文件中.不保证它甚至是正确的(很确定它是,并且跳过长度-1也排序),但是我知道它没有挂起,所以它有它为它= P

// quicksort for ints
static void quicksort_ints(int *arr, int left, int right)
{
    int p = (left+right)/2;    // as good as any
    int l = left, r = right;   // movable indicies

    while (l <= r)
    {
        while (arr[l] < arr[p])
            ++l;
        while (arr[r] > arr[p])
            --r;
        if (l <= r)
        {
            int tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;
            ++l;
            --r;
        }
    }

    if (left < r)
        quicksort_ints(arr, left, r);
    if (l < right)
        quicksort_ints(arr, l, right);
}
Run Code Online (Sandbox Code Playgroud)