c - 使用 pow() 报告的 SIGSEGV

标签 c debugging segmentation-fault

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

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

最佳答案

你有没有想过:

int i,j,p[2000], a[5000000],num,count,tmp;

可能会将您推到非常接近或完全越过堆栈空间的边缘?那就是

4 + 4 + 8000 + 20000000 + 4 + 4 + 4

字节

即您有一个19.08 兆字节 堆栈空间声明。至少考虑动态分配 a。当我将其更改为:

int *a = malloc(5000000 * sizeof(*a));

并重新运行代码,它已经很好地解决了您遇到的段错误。不幸的是,它死在了这个位置:

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
    }
}

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

static const int a_max = 5000000;
int *a = malloc(a_max*sizeof(*a));

在循环中:

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;
    }
}

这会让您完成所有设置。最后一件事是快速排序算法本身,它看起来也有问题。我强烈建议从较小的数据大小开始进行调试。

祝你好运。


编辑 如果您需要引用快速排序算法,我在我的一个垃圾文件夹中的源文件中找到了一个。不能保证它是正确的(很确定它是正确的,并且也跳过长度为 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);
}

关于c - 使用 pow() 报告的 SIGSEGV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14579104/

相关文章:

在 WordPress 中调试 cron 任务

当数据复制/扫描/读取到未初始化的指针时崩溃或 "segmentation fault"

c - unix 守护进程因未知原因停止且没有 coredump

c - 查找在 epoll 实例中注册了哪些描述符

node.js - 在webstorm中调试node js

javascript - 如何跟踪 javascript 事件(点击)在崩溃前经历了哪些函数?

CUDA BFS 巨图(seg.fault)

c - 没有任何非法访问的随机段错误

c - 如何强制两个进程在同一个CPU上运行?

c - 查找连续设置/未设置位的 block