[英]Getting a C++ segmentation fault
我在linux服务器中,当我尝试执行该程序时,它返回了分段错误。 当我使用gdb尝试找出原因时,它会返回。
Starting program: /home/cups/k
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401128 in search(int) ()
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.192.el6.x86_64 libgcc-4.4.7-17.el6.x86_64 libstdc++-4.4.7-17.el6.x86_64
我不能完全解释这一点。 在我的程序中,我有一个名为“ search()”的函数,但我看不到任何会导致段错误的东西。 这是函数def:
int search (int bit_type) { // SEARCH FOR A CONSEC NUMBER (of type BIT_TYPE) TO SEE IF ALREADY ENCOUNTERED
for (int i = 1; i <= MAX[bit_type]; i++) { //GO THRU ALL ENCOUNTERED CONSEC NUMBERS SO FAR (for type BIT_TYPE)
if (consec == r[bit_type][i]) // IF: FOUND
return i; // -----> RETURN INDEX OF RECORDED CONSEC_NUM
}
// IF: NOT FOUND
r[bit_type][++MAX[bit_type]] = consec; // -----> INCREMENT MAX[bit_type] & RECORD NEW CONSEC_NUM -------> ARRAY[MAX]
n[bit_type][MAX[bit_type]] = 1;
return (MAX[bit_prev]); // -----> RETURN THE NEWLY FILLED INDEX
}
全局功能:
int MAX[2];
int r[2][200];
int n[2][200];
因为您没有程序的其余部分,所以注释对您来说毫无用处。但是您可以忽略它们。
但是你们看到我想念的东西吗?
从此处的代码链接,这只是一个错误:
int *tmp = new int[MAX[0]];
for (int y = 0; y <= MAX[0]; y++) {
tmp[y] = 1;
}
您在上一次迭代中越界。 您为数组分配了MAX[0]
项目,在上一次迭代中,您正在访问tmp[MAX[0]]
。
该循环应为:
int *tmp = new int[MAX[0]];
for (int y = 0; y < MAX[0]; y++) {
tmp[y] = 1;
}
或更好:
#include <algorithm>
//...
std::fill(tmp, tmp + MAX[0], 1); // no loop needed
或使用new[]
跳过动态分配,并使用std::vector
:
#include <vector>
//...
std::vector<int> tmp(MAX[0], 1);
通常,您有多个执行此操作的循环:
for (int i = 1; i <= number_of_items_in_array; ++i )
然后使用array[i]
访问数组。 for
循环条件中的<=
令人怀疑,因为它会在上一次迭代时尝试使用越界索引访问数组。
另一个例子是这样的:
long sum(int arr_r[], int arr_n[], int limit)
{
long tot = 0;
for (int i = 1; i <= limit; i++)
{
tot += (arr_r[i])*(arr_n[i]);
}
return tot;
}
在这里, limit
是数组中元素的数量,您在最后一次迭代中访问arr_r[i]
,从而导致未定义的行为。
数组从0到n - 1
索引,其中n
是元素总数。 在尝试伪造基于1的数组时,几乎总是会在代码库内部的某些地方导致这些类型的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.