c - fclose causing exc_bad_access -
i can't figure out why fclose() in c program causing bad access. working fine , changed if condition print when strings not equal eachother , started causing problems. apart bad access error, not printing "newfile.txt"
#include<stdio.h> #include<stdlib.h> #include <string.h> int main() { file * cfile; file *outputfile; file *newfile; cfile = fopen("input.in", "r"); if (cfile == null){ printf("bad input file"); } newfile = fopen("newfile.txt", "w+"); if (newfile == null){ printf("bad newfile"); } char tempstring[15]; char tempstring2[15]; //get each line in cfile while (fscanf(cfile, "%15s", tempstring) != eof) { outputfile = fopen("outputlotnum.txt", "r"); //open/(or reopen) outputfile check lines if (outputfile == null){ printf("bad outputfile"); } //get each line in outputfile while(fscanf(outputfile, "%15s", tempstring2) != eof){ //if line cfile doesn't match line outputfile, //then go ahead , print line newfile.txt if (strcmp(tempstring, tempstring2) != 0){ fprintf(newfile,"%15s \n", tempstring2); } //else don't print , continue on next line } fclose(outputfile); //close outputfile after checking lines match } fclose(newfile); //throws bad access fclose(cfile); return 0; }
some reasons library functions seg faulting include passing bad parameters function or have memory scribbler. suspect in case have overflowed 1 or both temp string arrays on stack , have corrupted file handles. it's not safe operation fscanf/scanf buffer unless can guarantee string read fit buffer.
to confirm print out file handles after open, , again before close. should same. if not have accidentally overwritten them.
Comments
Post a Comment