Shawn Wilde

Sales Development Representative at UBERDOC

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 &lt;stdio.h&gt;

#include &lt;stdlib.h&gt;

int main()

{

int n, i;

int *a;

scanf("%d", &amp;n);

a = (int*)malloc(n*sizeof(int));

for(i=0; i&lt;n; i++)

{

scanf("%d", &amp;a[i]);

}

for(i=0; i&lt;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 &lt; n-1</code>:

<code>for(i=0; i&lt;n-1; i++)

{

scanf("%d", &amp;a[i]);

}

</code>

Links


Org chart


Teams

This person is not in any teams