I allocate memory for my 2d array, it works... but not correctly. When I use valgrind to see if I allocate and free well my array, I see that I free only 29 blocs on 445. The other problem is that my array got 11 columns for 20 lines, so 220 blocs I think. My results aren't correct, isn't it? How can I fix it?
There is my code, thank you in advance for your answers.
EDIT: My program should work with ncurses library. Should I really remove all what is link to?
There is all my code this time:
#include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
initscr();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
if (init_board() == -1)
return (-1);
while (1)
refresh();
endwin();
return (0);
}
void print_board(int **tab) {
int i;
int line;
i = 0;
printw("------------\n");
while (i < 20) {
line = 11;
printw("| ");
while (line-- > 0) {
tab[i][line] = 0;
if (tab[i][line] == 0)
printw("* ");
}
printw("|\n");
i++;
}
wprintw(stdscr, "------------\n");
}
int **board_size(int **tab) {
int i;
i = 0;
while (i < 20) {
if ((tab[i] = (int *)malloc(sizeof(int) * 11)) == NULL) {
wprintw(stdscr, "%s\n", "Second malloc's tab failed.");
return (NULL);
}
i++;
}
return (tab);
}
void free_board(int **tab) {
int i;
i = 0;
while (i < 20) {
printw("%d\n", i);
free(tab[i]);
i++;
}
free(tab);
}
int init_board() {
int **tab;
tab = NULL;
if ((tab = (int **)malloc(sizeof(int*) * 20)) == NULL) {
wprintw(stdscr, "%s\n", "First malloc's tab failed.");
return (-1);
}
if ((tab = board_size(tab)) == NULL)
return (-1);
print_board(tab);
free_board(tab);
return (0);
}