Stack smashing detected and no source for getenv

272 views Asked by At

I'm having the weirdest problem ever when programming in C. My function sometimes runs and other times it doesn't, and even though I tried searching for these errors (stack smashing detected and no source for getenv) I can't seem to find the answer to why it fails sometimes. I tried debugging it and it only has a problem in the last character (a "}"), so it runs all those other functions (and they have been tested a lot separately) but sometimes it just falls apart and doesn't run the last function (it works, that I can guarantee, because some other times it even runs inside this function). Also the few last times I ran the function it gave Segmentation Fault even though sometimes it ran all the way to the end. Is there any way I can debug this problem? Here goes my code:

void main(int argc, char * argv[]) {
FILE * fin=fopen(argv[1],"r");
char v[1024];
int col;
matrix m=emptyS();
while(fscanf(fin, "%s",v)!=EOF) {
    int i=0;
    int * w = (int*) malloc(sizeof (int));
    int str=strlen(v);
    int size=0;
    while(i<str) {
        char a[4];
        int y;
        for(y=0;y<4;y++)
            a[y]='\0';
        int x=0;
        while(v[i]!=',') {
            a[x]=v[i];
            i++;
            x++;
        }
        i++;
        size++;
        w=realloc(w,size*sizeof(int));
        w[size-1]=atoi(a);
    }
    m=add(m,w,size);
    col=size;
}
fclose(fin);
graphW wg=discWD(col-1);
int k=0;
while(k<(col-2)) {
    int j=k+1;
    while(j<(col-1)) {
        wg=add_Wedge(wg,k,j,mi(m,k,j,col));
        j++;
    }
    k++;
}
        int* ms=MST(wg);
graph gbayes=tree(wg,ms);
bayes b=newBN(gbayes,m);
FILE * fout=fopen(argv[2],"w");
serialize(b,fout);
fclose(fout);
}  

Thank you in advance!

1

There are 1 answers

1
Jens Gustedt On BEST ANSWER

You don't check x for going out of bounds. Valgrind would have told you.

while(i<str) {
        char a[4] = { 0 };
        int x=0;
        while(v[i]!=',') {
            a[x]=v[i]; /* here you access a[x] without check for x */
            i++;
            x++; /* Here it may go >= 4*/
        }
        i++;
        size++;
        w=realloc(w,size*sizeof(int));
        w[size-1]=atoi(a);
    }