Shawn Wilde has worked for UBERDOC, Inc. since 2022 as a Sales Development Representative and for Patients First Foundation since 2021 as an SDR.
I have a problem with the following code:
<code>#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
int *a;
scanf("%d", &n);
a = (int*)malloc(n*sizeof(int));
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
for(i=0; i<n; i++)
{
printf("%d\n", a[i]);
}
free(a);
return 0;
}
</code>
When I run this code, it gives me the following error:
<code>*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x09d7e008 ***
</code>
What is wrong with this code?
A:
This error is usually caused by a buffer overflow (i.e. writing more data than allocated for the buffer).
In your case, you are allocating memory for <code>n</code> elements, but you are reading <code>n+1</code> elements from the input.
To fix this, you should change the loop condition to <code>i < n-1</code>:
<code>for(i=0; i<n-1; i++)
{
scanf("%d", &a[i]);
}
</code>
Links
Sign up to view 0 direct reports
Get started