Вы пропустили разыменование mat несколько раз, я имею в виду, что mat
должно быть (*mat)
:
void buildBoard(int*** mat, int size)
{
*mat = (int**)malloc(size * sizeof(int*));
if (*mat == NULL)
{
printf("Bye\n");
exit(1);
}
for (int i = 0; i < size; ++i)
{
(*mat)[i] = (int*)malloc(size * sizeof(int));
if ((*mat)[i] == NULL)
{
printf("Bye\n");
exit(1);
}
}
}
void initMat(int*** mat, int size)
{
printf("Please enter a numbers:\n");
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
scanf("%d", &(*mat)[i][j]);
}
}
}
Я также удалил бесполезную переменную num
Компиляция и выполнение:
pi@raspberrypi:/tmp $ gcc -g -pedantic -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
Please enter a size of the matrix:
2
Please enter a numbers:
1
2
3
4
1 2
3 4
Под valgrind :
pi@raspberrypi:/tmp $ valgrind ./a.out
==4232== Memcheck, a memory error detector
==4232== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4232== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4232== Command: ./a.out
==4232==
Please enter a size of the matrix:
2
Please enter a numbers:
1
2
3
4
1 2
3 4
==4232==
==4232== HEAP SUMMARY:
==4232== in use at exit: 24 bytes in 3 blocks
==4232== total heap usage: 5 allocs, 2 frees, 2,072 bytes allocated
==4232==
==4232== LEAK SUMMARY:
==4232== definitely lost: 8 bytes in 1 blocks
==4232== indirectly lost: 16 bytes in 2 blocks
==4232== possibly lost: 0 bytes in 0 blocks
==4232== still reachable: 0 bytes in 0 blocks
==4232== suppressed: 0 bytes in 0 blocks
==4232== Rerun with --leak-check=full to see details of leaked memory
==4232==
==4232== For counts of detected and suppressed errors, rerun with: -v
==4232== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@
Конечно valgrind указывает на утечки памятипоскольку вы не освобождаете выделенную память
Обратите внимание, что бесполезно указывать адрес переменной в initMat , может быть:
void initMat(int** mat, int size)
{
printf("Please enter a numbers:\n");
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
scanf("%d", &mat[i][j]);
}
}
}
конечно, также изменив свою декларацию и вызов в main
Ранее я также удалил free , который вы имели в:
if (mat[i] == NULL)
{
printf("Bye\n");
free(mat[i]);
}
потому что на самом деле вы свободны NULL