0

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*/ 

2 Answers 2

2

Looks like you're changing line inside the loop, so you're not free'ing the same pointer you got from malloc()

You should make a copy of the pointer for modifying in the loop and leave the original alone.

You might also want to consider doing something less horrid than allocating a potentially enormous amount of memory up front, just in case, and then using it without error checks.

(you don't check the memory was ever allocated, and your fgets always assumes you have INT_MAX bytes available even after you increment the pointer into the buffer).

Sign up to request clarification or add additional context in comments.

2 Comments

I must prevent memory leaks. How can I fix my code? @JasonD
Backup what you received from malloc() to later use it for free()ing.
1

You lose your base address here:

++line; /*next address on line*/ 

Store line in a temp variable like this:

char *line = malloc(INT_MAX * sizeof(char)); char *_temp = line ; 

And at the end of function:

free(_temp); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.