I want the main returns the position of the occurrences of "mdl" in "dati". I set up the "schema" function to find the starting point of each occurrence, but when i run the program from the command line, it returns:
Segmentation fault: 11
I don't know how to fix the problem. Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
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;
}
I have to use the function to find the occurrences, I cannot use other ways.
I suppose the error lies in the following code segment:
Note that you pass
dati
, which is an integer array of sizen
, astesto
and you passn
as the value fornT
. Hence,testo
is of sizenT
. But in you loop, wherei
potentially runs untilnt-1
, you accesstesto[i+7]
, which exceeds the boundaries oftesto
, right?You're dereferencing the pointer
soluzione
, but it was never initialized with a value:Reading an uninitialized value, as well as subsequently dereferencing that uninitialized value, invokes undefined behavior. In this case, it manifests in a segmentation fault.
You don't need a pointer in this case. Just declare the variable as an
int
.You also don't initialize
start
. As a result, you index intotesto
at an unknown location which could be outside the bounds of the array. This also invokes undefined behavior.EDIT:
It looks like you're actually returning the wrong datatype from
schema
. If you want to return a pointer to the local arrayr
(which in this case is fine since it's declared asstatic
, the function needs to return anint *
and you shouldreturn r
.Then in
main
you would keepsoluzione
as a pointer but assign to it directly.