I need to create a dynamic array and put five number, after there is another input which is how much I have to increase the array size. When all input are ended I am going to increase the array size and put numbers inside.
everything works but free return me this error: "free(): invalid next size (fast): 0x00000..."
I think there are errors inside "extend" function
void extend(int *V, int n, int s)
{
int *pt;
pt = realloc(V, n*sizeof(int));
int i;
pt[5]=s;
for(i=6;i<(5+n);i++)
pt[i] = pt[i-1]*2;
}
int main()
{
int *v;
int n,i, sum;
sum = 0;
v = malloc(sizeof(int)*5);
for(i=0;i<5;i++)
{
scanf("%d", &v[i]);
sum+=v[i];
}
scanf("%d", &n);
extend(v,n,sum);
for(i=0;i<(5+n);i++)
printf("%d\n", v[i]);
free(v);
return 0;
}
The function does not change the original variable
v
. It should be defined at least likeOr
And the function should be called lije
Take into account that the function is unsafe because in general
n
can be less than or equal to 5. And this statementcan result in undefined behavior.
Or the function shall allocate n + 5 elements. For example
Also the using of this magic number 5 is unclear and does not make sense.