I am new to dynamic allocation in c and I am getting heap corruption error at the call of the free()
function.
The whole code is supposed to simulate the reallocation function realloc()
and it works fine until the end. I ran the code multiple times in debugger mode step by step and the error appears at the end. If someone could help me I would be very grateful.
#include <stdlib.h>
#include <stdio.h>
void realocare(int **v, int n,int m)
{
int *aux;
unsigned int i;
aux = (int*)malloc(m*sizeof(int));
for (i = 0; i < m; i++)
aux[i] = v[i];
*v = (int*)malloc(n*sizeof(int));
for (i = 0; i < m; i++)
v[i] = aux[i];
free(aux);
}
void afisare(int *v, int n,int i)
{
for (i = 0; i < n; i++)
printf_s("%d ", v[i]);
printf_s("\n");
}
int main()
{
int *v;
unsigned int n,i,m;
scanf_s("%u", &n);
v = (int*)malloc(n*sizeof(int));
for (i = 0; i < n; i++)
scanf_s("%d", &v[i]);
m = n;
printf("%d", m);
afisare(v, n, i);
n++;
realocare(&v, n,m);
v[n - 1] = 9000;
afisare(v, n, i);
free(v);
return 0;
}