After debugging i get this error message : HEAP CORRUPTION DETECTED after normal block (#55). If I increse the size of the array (no_of_days+1), it’s working, but i don’t know if it’s right.
What i am doing wrong?
int main()
{
int no_of_days=0;
int no_operations=0;
int *a;
int i;
FILE *pfile1=NULL;
FILE *pfile2=NULL;
char *filename1="input.txt";
char *filename2="output.txt";
pfile1=fopen(filename1, "r");
if(pfile1==NULL)
{
printf("Error on opening the file %s.",filename1);
return 0;
}
fscanf(pfile1,"%d%d",&no_of_days,&no_operations);
a=(int*)malloc((no_of_days)*sizeof(int));
if(a==NULL)
{
printf("Memory allocation failed.");
return 0;
}
for(i=1;i<=no_of_days;i++)
{
fscanf(pfile1,"%d",&a[i]);
}
pfile2=fopen(filename2,"a");
if(pfile2==NULL)
{
printf("Memory allocation failed!",filename2);
}
for(i=1;i<=no_of_days;i++)
{
fprintf(pfile2,"%d",a[i]);
}
free(a);
fclose(pfile1);
fclose(pfile2);
Indexing starts from 0 so accessing
a[no_of_days]is illegal. Change thatforline to: