Reputation: 151
So I am executing a code that reads values from a file and process them. The workable code is below, and I can provide the file too.
FILE *fp1, *fp2;
short input_filt=0, output_filt=-32767;
unsigned short alpha = 23528, i=0;
fp1=fopen("sine1kHz.mat", "r");
if(fp1==NULL)
return 0;
fp2=fopen("filter.mat", "w");
for (i=0; i<1024; i++)
{
fscanf(fp1, "%d", &input_filt);
output_filt=(output_filt*alpha)+(input_filt*(1-alpha));
fprintf(fp2, "%d %d\n", input_filt, output_filt);
}
fclose(fp1);
fclose(fp2);
return 0;
So I debugged and the reading from the file is absolutely fine. So there are no problems while I am in the loop (no access to values non existent). However, once I leave the loop the program crashes and Microsoft Visual Studio gives me this message:
"Run-Time Check Failure #2 - Stack around the variable 'input_filt' was corrupted."
Any idea why this is happening and how to fix it? Thank you!
Upvotes: 0
Views: 31
Reputation: 223689
You're using the wrong format specifier for scanf
.
The %d
format specifier to scanf
expects an int *
argument, however you're passing in a short *
. Since a short
is smaller than an int
on your system, scanf
will write past the memory used by input_filt
when the value is read in.
You want to use %hd
instead which tells it to expect a short *
.
fscanf(fp1, "%hd", &input_filt);
Note that it isn't strictly necessary to use %hd
for printf
because a short
value passed to a variadic function will be automatically promoted to int
.
Upvotes: 2