[英]Segmentation fault (core dumped). Heapsort
I have this heapsort program which run on Windows, but is giving segmentation fault on ubuntu 14.04. 我有这个可以在Windows上运行的heapsort程序,但是在ubuntu 14.04上出现了分段错误。
#include<stdio.h>
#define N 5000
int arr[N];
int size=N-1;
int parent(int i)
{
return (i-1)/2;
}
int lchild(int i)
{
return 2*i+1;
}
int rchild(int i)
{
return 2*i+2;
}
void maxheapify(int arr[],int i)
{
int larg,t;
int l=lchild(i);
int r=rchild(i);
if(arr[l]>arr[i] && l<=size)
larg=l;
else
larg=i;
if(arr[r]>arr[larg] && r<=size)
larg=r;
if(larg!=i)
{
t=arr[larg];
arr[larg]=arr[i];
arr[i]=t;
maxheapify(arr,larg);
}
}
void buildmaxh(int arr[])
{
int i;
for(i=N/2-1;i>=0;i--)
maxheapify(arr,i);
}
void heapsort(int arr[])
{
int i,t;
buildmaxh(arr);
size--;
for(i=N-1;i>0;i--,size--)
{
t=arr[0];
arr[0]=arr[i];
arr[i]=t;
maxheapify(arr,0);
}
}
int main()
{
srand(time(NULL));
int i;
for( i=0;i<N;i++)
arr[i]=rand()%101;
heapsort(arr);
printf("done\n\n");
return 0;
}
What is the source of error? 错误的根源是什么? How can I remove this error? 如何清除此错误?
I tried debugging the code using gdb as explained here . 我试着用gdb作为解释调试代码在这里 。 But I can't compile the program as described in the answer. 但是我不能按照答案中的描述编译程序。 I used command gcc myfile.c -ggdb myfile. 我使用了命令gcc myfile.c -ggdb myfile。 Also,using command: gcc myfile.c -o myfile I compiled the program successfully, which gave me segmentation error. 另外,使用命令:gcc myfile.c -o myfile我成功编译了程序,这给了我分段错误。 What am I doing wrong? 我究竟做错了什么? Thanks. 谢谢。
The error occurs in maxheapify
when you check which of the children is larg
: 在出现的错误maxheapify
当你检查哪些孩子是larg
:
if (arr[l]>arr[i] && l<=size) ...
You've got the checks the wrong way round. 您以错误的方式获得了支票。 When you read arr[l]
, l
might be out of bounds, which is a segmentation violation. 当您阅读arr[l]
, l
可能会超出范围,这是分段违反。 If you check the bounds first like this: 如果您首先像这样检查边界:
if (l<=size && arr[l]>arr[i]) ...
the read access won't happen if l
is out of bounds. 如果l
超出范围,则不会发生读取访问。 (Remember that the &&
and ||
operators short-circuit the evaluation: In a && b
, b
is never checked if a
is already false
, because there's no way the whole expression can be true.) (记住&&
和||
运营商短路评价:在a && b
, b
是从来没有检查,如果a
已经是false
,因为没有办法了整个表达式可以实现的。)
The same goes for the check of arr[r]
some lines after that. 之后检查arr[r]
几行也是如此。
Also, please include <stdlib.h>
and <time.h>
; 另外,请包含<stdlib.h>
和<time.h>
; they are needed for your randomisation code. 它们是您的随机代码所必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.