请。
程序删除矩阵中的一行。一切正常,但无法从已删除的行中释放内存。
请告诉我,这怎么办?
#include "cdio.h"
#include "func.h"
int main()
{
long int **matrix = NULL;
size_t n = 5;
size_t m = 4;
matrix = matrix_allocate(n, m);
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < m; j++)
matrix[i][j] = rand() % 100;
puts("OLD MATRIX:");
print_matrix(matrix, n, m);
int pos = 0;
puts("enter position:");
scanf("%d", &pos);
for (size_t i = pos; i < n-1; i++)
matrix[i] = matrix[i+1];
n--;
long int **temp = realloc(matrix, n * sizeof(long int));
if (temp)
{
matrix = temp;
temp = NULL;
}
puts("NEW MATRIX:");
print_matrix(matrix, n, m);
for (int i = 0; i < n; i++)
free(matrix[i]);
free(matrix);
return 0;
}
==5203== HEAP SUMMARY:
==5203== in use at exit: 32 bytes in 1 blocks
==5203== total heap usage: 9 allocs, 8 frees, 2,280 bytes allocated
==5203==
==5203== LEAK SUMMARY:
==5203== definitely lost: 32 bytes in 1 blocks
==5203== indirectly lost: 0 bytes in 0 blocks
==5203== possibly lost: 0 bytes in 0 blocks
==5203== still reachable: 0 bytes in 0 blocks
==5203== suppressed: 0 bytes in 0 blocks
键入错误时
realloc
:数组中的类型是指针,而不是
long int
.Чтобы освободить память строки нужно просто сделать
free
。