I use malloc in a function. End of the function I call free function to avoid memory leak. But if I call free I get segmentation fault when I don't program works normally. Can anybody know why? I marked the places with comments(If I put free(line) here I get seg fault. If I don't it occurs memory leak). Here is my code:
void checkOccurrences(FILE *inp, char *wanted, int lineCount, int limit) { char option; char *line = malloc(INT_MAX * sizeof(char)); int i, dif, lineNumber = 0; /*i for count, dif means difference*/ char *temp, *checkpoint; while(fgets(line, INT_MAX, inp) != NULL) /*gets line by line*/ { dif = strlen(line) - strlen(wanted); /*for limit for loop*/ ++lineNumber; /*increase line number*/ for(i = 0; i < dif; ++i) /*difference times loop*/ { temp = strstr(line, wanted); /*first occurrence address on line*/ if(temp != NULL) /*if there is occurrence*/ { /*temp>checkpoint condition means if there is new occurrences*/ if(temp > checkpoint) { ++lineCount; if((lineCount % limit) == 0) { printLine(lineNumber); checkpoint = temp; printf("more(m) or quit(q) "); scanf(" %c", &option); /*get option*/ if(option == 'q') { /*If I put free(line) here I get seg fault*/ /*If I don't it occurs memory leak*/ exit(0); /*end program*/ } } else { printLine(lineNumber); checkpoint = temp; } } } ++line; /*next address on line*/ } } /*If I put free(line) here I get seg fault*/ /*If I don't it occurs memory leak*/ } /*GIT121044025*/