Hello, help solve the problem. The problem is to clean up the multidimensional array before exiting in case of not allocating memory. I already asked a similar question about cleaning before leaving, many recommend not to rely on the OS, but to clean it myself, but I have a problem. It is necessary to clear the entire multidimensional array, but I do not have enough "mind" to implement cleaning. If in the first and in the second case - you can think and implement cleaning, then in the third it is difficult. In C_ONE and C_TWO there can be, for example, any number, this is just an example.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define C_ONE 2 #define C_TWO 2 int main(void) { char ***test = NULL; for (unsigned char i = 0; i < C_ONE; i++) { test = (char ***) realloc((i + 1) * sizeof(char **)); if (test == NULL) { // тут всё просто if (i > 0) { for (unsigned char j = 0; j < i; j++) { for (unsigned char k = 0; k < C_TWO; k++) free(*(*(test + j) + k)); free(*(test + j)); } free(test); } exit(-1); } *(test + i) = (char **) malloc(C_TWO * sizeof(char *)); if (*(test + i) == NULL) { /** * Хорошо, а тут как "всё" очистить? **/ exit(-1); } for (unsigned char m = 0; m < C_TWO; m++) { *(*(test + i) + m) = (char *) malloc((1 + 1) * sizeof(char)); if (*(*(test + i) + 0) == NULL) { /** * Если во втором случае можно подумать и написать, * тогда в этом уже сложно. **/ exit(-1); } strcpy(*(*(test + i) + m), "W"); } } // если всё успешно, то очистка, как и в первом случае. for (unsigned char m = 0; m < C_ONE; m++) { for (unsigned char o = 0; o < C_TWO; o++) free(*(*(test + m) + o)); free(*(test + m)); } free(test); return 0; }