为什么我会出现分段错误?
如果我将大于 100 的值作为第二个参数传递给 BinaryInsertionSort,则会出现分段错误。
int
BinarySearch (int a[], int low, int high, int key)
{
int mid;
if (low == high)
return low;
mid = low + ((high - low) / 2);
if (key > a[mid])
return BinarySearch (a, mid + 1, high, key);
else if (key < a[mid])
return BinarySearch (a, low, mid, key);
return mid;
}
void
BinaryInsertionSort (int a[], int n)
{
int ins, i, j;
int tmp;
for (i = 1; i < n; i++) {
ins = BinarySearch (a, 0, i, a[i]);
if (ins < i) {
tmp = a[i];
memmove (a + ins + 1, a + ins, sizeof (int) * (i - ins));
a[ins] = tmp;
}
}
}
If I pass a value greater than 100 as the second argument to BinaryInsertionSort, I get a segmentation fault.
int
BinarySearch (int a[], int low, int high, int key)
{
int mid;
if (low == high)
return low;
mid = low + ((high - low) / 2);
if (key > a[mid])
return BinarySearch (a, mid + 1, high, key);
else if (key < a[mid])
return BinarySearch (a, low, mid, key);
return mid;
}
void
BinaryInsertionSort (int a[], int n)
{
int ins, i, j;
int tmp;
for (i = 1; i < n; i++) {
ins = BinarySearch (a, 0, i, a[i]);
if (ins < i) {
tmp = a[i];
memmove (a + ins + 1, a + ins, sizeof (int) * (i - ins));
a[ins] = tmp;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在传入一个数组 a[]。它必须足够大,以使值 hi 和 low 在范围内。
例如,如果您传入一个大小为 1 的数组,且 low = 0。hi = 2,则 mid = 1,这将超出范围(大小为 1 的数组只能取消引用 a[0],a[1 ] 将超出范围)。
You are passing an array a[] in. it must be large enough that the values hi and low are in range.
For example, if you pass an array of size 1 in, and low = 0. hi = 2, then mid = 1 which will be out of range (an array of size 1 can only have a[0] dereferenced, a[1] will be out of range).
很难说,使用调试器。它将帮助您定位分段错误所在的位置,以及发生分段错误时不同变量的值是什么。
-g
选项的 g++ 进行编译)Hard to tell, Use a debugger. It will help you locate where the segmentation fault is located, and what are the value of different variable when the segmentation fault occurs.
-g
option)可能是因为堆栈溢出?您正在递归调用
BinarySearch
。n
的值越大,消耗的堆栈空间就越多。我希望在这种情况下您会看到堆栈溢出错误,但我不知道您的环境...假设您没有使用调试器,这是一种快速测试方法这将首先找到出现错误的确切点(您提到了 100,但不清楚您是否不会在 99 时出现错误...)。
完成后,尝试增加每次递归调用
BinarySearch
消耗的堆栈空间量(添加一些额外的局部变量,并对它们进行足够的处理,以免它们被优化掉)。您应该会发现您无法再成功完成 99(或之前的最大值)。Could be because of stack overflow? You're calling
BinarySearch
recursively. The greater the value ofn
, the more stack space you'll consume. I would expect that you'd see a stack overflow error in such a case, but I don't know your environment...Assuming that you aren't using a debugger, a quick way to test this would be to first find the exact point at which you get the error (you mentioned 100, but it's not clear that you wouldn't get the error with 99...).
Once you have that, try increasing the amount of stack space consumed by each recursive call to
BinarySearch
(add a few additional local variables, and do enough with them that they won't be optimized out). You should see that you can no longer successfully do 99 (or whatever your previous maximum was).