How to fix segmentation fault 11 error? [duplicate]

无人久伴 提交于 2019-12-04 21:40:36

You're dereferencing the pointer soluzione, but it was never initialized with a value:

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

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.

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

You also don't initialize start. As a result, you index into testo 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 array r (which in this case is fine since it's declared as static, the function needs to return an int * and you should return r.

Then in main you would keep soluzione as a pointer but assign to it directly.

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);

I suppose the error lies in the following code segment:

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]) {

Note that you pass dati, which is an integer array of size n, as testo and you pass n as the value for nT. Hence, testo is of size nT. But in you loop, where i potentially runs until nt-1, you access testo[i+7], which exceeds the boundaries of testo, right?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!