简体   繁体   English

使用C ++中的字符串堆排序代码获取分段错误

[英]Getting Segmentation Fault with string Heap Sort code in C++

int heapSize = 20; //variable 
int left(int i) {
return (2 * i) + 1;
}

int right(int i) {
return (2 * i) + 2;
}

void heapify(string arr[], int i) {
int l = left(i);
int great=0;
int r = right(i);
if ( ((strcmp(arr[l].c_str(),arr[i].c_str()))>0) && (l < heapSize)) {
great = l;
}
else {
great = i;
}

if ( ((strcmp(arr[r].c_str(),arr[great].c_str()))>0) && (r < heapSize)) {
great = r;
}
if (great != i) {
string temp = arr[i];
arr[i] = arr[great];
arr[great] = temp;
heapify(arr, great); //Getting segment here 
}

}

void BuildMaxHeap(string arr[]) {
for (int i = (heapSize - 1) / 2; i >= 0; i--) {
heapify(arr, i);
}
}

void HeapSort(string arr[]) {
BuildMaxHeap(arr); //
for (int i = heapSize; i > 0; i--) {
string temp = arr[0];
arr[0] = arr[heapSize - 1];
arr[heapSize - 1] = temp;
heapSize = heapSize - 1;
heapify(arr, 0);
}

}

Getting segmentation fault with this string heap sort code for heapSize larger than 15, for example 20 elements. 对于大于15(例如20个元素)的heapSize,使用此字符串堆排序代码获取分段错误。 Any idea about the reason? 知道原因吗?

I backtraced it in gdb and I get this 我在gdb中追溯了它,得到了

#0  0x0038124b in ?? () from /lib/tls/i686/cmov/libc.so.6
#1  0x08048f62 in heapify(std::string*, int) ()
#2  0x08049050 in heapify(std::string*, int) ()
#3  0x080490ae in BuildMaxHeap(std::string*) ()
#4  0x080490d3 in HeapSort(std::string*) ()
#5  0x080494f5 in main ()

So, what is wrong with the heapify function? 那么,heapify函数有什么问题呢?

if s中,在尝试比较字符串之前,应检查索引是否在数组的边界内:

if ( (l < heapSize) && (arr[l] > arr[great]) ) {

It is your array indexes. 它是您的数组索引。 Check out the left & right functions and the for loop parameters that feed them. 检查出leftright功能和养活他们的for循环参数。 With an odd numbered 'heapSize' value left will eventually return an index past the end of the array. 以奇数“HEAPSIZE”值left终有回报指数越过数组的结尾。 With an even numbered 'heapSize', right will do it. 随着偶数“堆大小”, right会做到这一点。

eg when 'heapSize' == 15, then the max 'i' passed to 'heapify' will be 7 ((15-1) / 2) . 例如,当'heapSize'== 15时,传递给'heapify'的最大值'i'将为7 ((15-1)/ 2) Pass that into 'left' and you get 15. Too big for the array, so it croaks when trying to get the string for the 'strcmp'. 将其传递到“ left”中,您将得到15。对于数组而言太大了,因此在尝试获取“ strcmp”的字符串时会嘎吱作响。

Maybe I've done something wrong, but I'm not getting your code to run regardless of heap size. 也许我做错了什么,但是无论堆大小如何,我都无法运行您的代码。

PS. PS。 build with '-g3' flag to get better debug symbols in gdb. 使用'-g3'标志进行构建,以在gdb中获得更好的调试符号。 g++ -g3 heap.cc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM