Ćwiczę alokację pamięci i przyszła pora żeby zwolnić pamięć w funkcji:
int main()
{int i;
int m,n;
int *p;
srand(time(NULL));
printf("Ile wierszy: ");
scanf("%d",&n);
printf("Ile kolumn: ");
scanf("%d", &m);
p=tablica(n,m);
wypisz(p,n,m);
zwolnij(p,n,m);
system("PAUSE");
return 0;
}
int * tablica(int n, int m)
{
int i,j;
int *k=(int*)malloc(sizeof(int)*n);
if(k==NULL)
return NULL;
for(i=0; i<n; i++)
{
k[i]=(int*)malloc(sizeof(int)*m);
if(k[i]==NULL)
return NULL;
}
for(i=0; i<n; i++)
for(j=0; j<m; j++)
*(k+(i*m+j)*sizeof(int))=rand()%100;
return k;
}
void wypisz (int *k,int n,int m)
{
int i,j;
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
printf("%d\t", *(k+(i*m+j)*sizeof(int)));
printf("\n");
}
}
void zwolnij(int *p, int n, int m)
{
int i,j;
for(i=0; i<n; i++)
free(p+m*i*sizeof(int)); //<- zakładam, że to tu się dzieje jakaś katastrofa
free(p);
p=NULL;
}
Program się wykonuje, losuje i wypisuje tablicę, ale potem wyskakuje błąd:
Windows has triggered a breakpoint in Alokacja.exe.
This may be due to a corruption of the heap, which indicates a bug in Alokacja.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while Alokacja.exe has focus.
The output window may have more diagnostic information
Przeszukałem trochę internetu, próbowałem na bazie innych kodów to poprawić, używałem tablicy (p[i]) do zwalniania pamięci, ale nic nie działa