如何修复分段错误11错误?

我希望main返回“dati”中出现“mdl”的位置。 我设置“schema”函数来查找每次出现的起点,但是当我从命令行运行程序时,它返回:

Segmentation fault: 11 

我不知道如何解决这个问题。 这是代码:

 #include  #include  #include  #include  int schema(int testo[], int nT, int modello[], int nM, int primo) { int i, j, k; static int r[12]; j=0; for(i=primo; i<nT; i++) { if(testo[i] == modello[0] && testo[i+1] == modello[1] && testo[i+2] == modello[2] && testo[i+3] == modello[3] && testo[i+4] == modello[4] && testo[i+5] == modello[5] && testo[i+6] == modello[6] && testo[i+7] == modello[7]) { r[j] = i+1; j++; } } return *r; } int main(int argc, char** argv) { FILE *in; FILE *out; int i, m; const int n = 100; int dati[n]; int *soluzione; int start; if ((in=fopen("dati.txt", "r"))==NULL){ return -1; } for(i=0; i<n; i++) { if (fscanf(in, "%d", &dati[i]) < 0){ fclose(in); return i; } } int mdl[] = {0,0,0,1,1,1,0,1}; m = sizeof(mdl)/sizeof(mdl[0]); *soluzione = schema(dati, n, mdl, m, start); for(i=0; i<12; i++) { printf("- risultato[%d] = %d\n", i, soluzione[i]); } //out = fopen("risultati.txt", "w"); //... fclose(in); return 1; } 

我必须使用该函数来查找事件,我不能使用其他方法。

您正在取消引用指针soluzione ,但它从未使用值初始化:

 int *soluzione; ... *soluzione = schema(dati, n, mdl, m, start); 

读取未初始化的值,以及随后取消引用该未初始化的值,将调用未定义的行为 。 在这种情况下,它表现为分段错误。

在这种情况下,您不需要指针。 只需将变量声明为int

 int soluzione; ... soluzione = schema(dati, n, mdl, m, start); 

你也没有初始化start 。 因此,您将索引到未知位置的testo ,该位置可能超出数组的范围。 这也会调用未定义的行为。

编辑:

看起来你实际上是从schema返回了错误的数据类型。 如果你想返回一个指向本地数组r的指针(在这种情况下很好,因为它被声明为static ,函数需要返回一个int * ,你应该return r

然后在main你将soluzione保留为指针但直接分配给它。

 int *schema(int testo[], int nT, int modello[], int nM, int primo) { ... return r; } int main(int argc, char** argv) { ... int *soluzione; ... soluzione = schema(dati, n, mdl, m, start); 

我想错误在于以下代码段:

 for(i=primo; i 

请注意,您将dati (大小为n的整数数组)作为testo传递,并将n作为nT的值传递。 因此, testo的大小为nT 。 但是在你循环中, i可能会运行到nt-1 ,你可以访问testo[i+7] ,它超出了testo的界限,对吧?