Hi all,
I am trying to read two .txt files, save them to two 1D arrays and record their length. Then I define two 2D arrays and allocate memory to them for further use. After these, I free all these memories. But I get errors when I debug:
Windows has triggered a breakpoint in aa.exe.
This may be due to a corruption of the heap, and indicates a bug in aa.exe or any of the DLLs it has loaded.
The output window may have more diagnostic information
The break point locates in close.c--_free_osfhnd(fh );
Here is my code, could you please check and let me know where the problem is?
Thanks a bunch!!
I am trying to read two .txt files, save them to two 1D arrays and record their length. Then I define two 2D arrays and allocate memory to them for further use. After these, I free all these memories. But I get errors when I debug:
Windows has triggered a breakpoint in aa.exe.
This may be due to a corruption of the heap, and indicates a bug in aa.exe or any of the DLLs it has loaded.
The output window may have more diagnostic information
The break point locates in close.c--_free_osfhnd(fh );
Here is my code, could you please check and let me know where the problem is?
Code:
long getFileSize(char *fileName){
long res = 0;
FILE *pFile;
if(fopen(fileName,"r+")==NULL){
printf("Cannot open file.\n");
res = 0;
}else{
pFile = fopen (fileName,"r+");
fseek (pFile,0,SEEK_END);
res = ftell(pFile);
fclose (pFile);
}
return res;
}
char* getSequence(char*fileName,long size){
char *res;
res=(char*)malloc(size*sizeof(char));
FILE *pFile;
pFile = fopen(fileName,"r+");
fgets(res,size-1,pFile);
fclose (pFile);
return res;
free(res);
}
void free2DArray(int **arr, int size)
{
for(int i=0 ; i<size; ++i)
free(arr[i]);
free (arr);
}
int main() {
//read sequences from files
char targetFile[] = "target.txt";
char queryFile[] = "query.txt";
long targetSize = getFileSize(targetFile)+1;
long querySize = getFileSize(queryFile)+1;
printf("targetSize is %d and querySize is %d\n",targetSize,querySize);
if(targetSize==0 || querySize==0){
printf("File error!\n");
exit(1);
}
char *targetSeq,*querySeq;
targetSeq = (char*)malloc(targetSize*sizeof(char));
querySeq = (char*)malloc(querySize*sizeof(char));
targetSeq = getSequence(targetFile,targetSize);
querySeq = getSequence(queryFile,querySize);
/* first we reserve memory for all the variables we will use */
int i,j,......;
int maxAlign = targetSize+querySize;
int **distance,**trace;
distance = (int**)malloc(querySize*sizeof(int*));
trace = (int**)malloc(querySize*sizeof(int*));
for(i=0;i<targetSize;i++){
*(distance+i) = (int*)malloc(targetSize*sizeof(int));
*(trace+i) = (int*)malloc(targetSize*sizeof(int));
}
free(targetSeq);
free(querySeq);
free2DArray(distance,targetSize);
free2DArray(trace,targetSize);
return 0;
}
Comment