Я придумал этот код с помощью @GWW, и теперь я не могу бесплатно
char **
.
Вот мой код (он просто читает входной файл и выводит на экран его имена):
/* deallocate2D
corresponding function to dynamically deallocate 2-dimensional array using
* malloc.
* accepts a char** as the "array" to be allocated, and the number of rows.
* as with all dynamic memory allocation, failure to free malloc'ed memory
* will result in memory leaks
*/
void deallocate2D(char** array, int nrows) {
/* deallocate each row */
int i;
for (i = 0; i < nrows; i++) {
free(array[i]);
}
/* deallocate array of pointers */
free(array);
}
int readInputFile(FILE *fp, char **file_images) {
num_lines = 0;
int s = 10;
char line[MAX_LENGTH];
char **final_filenames;
while (fgets(line, sizeof line, fp) != NULL) /* read a line */ {
if (line[0] != '\n') {
if (num_lines >= s) {
s += 100;
if ((file_images = (char**) realloc(file_images, s * sizeof (char*))) == NULL) {
printf("Error reallocating space for 2d array: %s\n", strerror(errno));
return -1;
}
}
if ((file_images[num_lines] = malloc(MAX_LENGTH * sizeof (char))) == NULL) {
printf("Error allocating space for 2d array: %s\n", strerror(errno));
return -1;
}
strncpy(file_images[num_lines], line, MAX_LENGTH);
if (file_images[num_lines] == NULL) {
printf("Strncpy failed: %s\n", strerror(errno));
return -1;
}
printf("name of file %d is: %s \n", num_lines, file_images[num_lines]);
num_lines++;
}
}
printf("Num_lines: %d\n",num_lines);
//realloc to number of lines in the file, to avoid wasting memory
if ((final_filenames = realloc(file_images, num_lines * sizeof (char*))) == NULL) {
printf("Error reallocating space for 2d array: %s\n", strerror(errno));
return -1;
} else {
file_images = final_filenames;
deallocate2D(final_filenames, num_lines);
}
return 0;
//don't forget to free lines 2d array! (here or at the end of the code)
}
int main(int argc, char *argv[]) {
//pixel* image;
char **images_filenames;
//check parameters
if (argc < 4) {
printf("Incorrect usage.\nPlease use \"./invert input_filename.ppm charWidth charHeight \"\n");
return -1;
}
printf("Opening input file [%s]\n", argv[1]);
FILE *fpin = fopen(argv[1], "r");
if (fpin == NULL) {
printf("Could not open input file\n");
return -1;
}
if ((images_filenames = ((char**) malloc(10 * sizeof (char*)))) == NULL) {
printf("Error allocating initial space for 2d array: %s\n", strerror(errno));
return -1;
}
if (readInputFile(fpin, images_filenames) == -1) {
printf("Error reading image filenames from input\n");
return -1;
}
fclose(fpin);
printf("###########\n");
deallocate2D(images_filenames, num_lines);
printf("Done!\n");
return 0;
}
Итак, я не понимаю, почему я не могу бесплатно
final_filenames
и images_filenames
.
Ошибка, которую выдает этот код:
*** glibc detected *** ./main: double free or corruption (!prev): 0x0986d228 ***
Как мне правильно освободить
мои массивы без ошибок?