All its doing is running functions but for some reason it doesn't break after I press r, it just runs the function then ends the program.
int main()
{
char key = 0;
PPMImage *img = NULL;
do {
puts("\tPress r to read in an image in ppm format");
puts("\tPress s to save image in ppm format");
puts("\tPress q to quit");
scanf(" %c", &key);
clear_to_end(stdin);
switch (key) {
case 'r':
load_file("fname");
free(img->data);
break;
case 's':
save_file(img);
break;
case 'q':
puts("\tTerminating program...");
break;
default:
puts("\tInvalid Input");
break;
}
} while (key != 'q');
}
The reason the program exits is it has undefined behavior:
load_file("fname"); may load the image file, but no side effect occurs on imgfree(img->data); dereferences null pointer img, causing a segmentation fault and program termination.Assuming load_file returns a pointer to PPMImage and your intent is to free a previously read image, change the code to:
case 'r':
if (img) {
// free the previous image
// write a function to free what was allocated
free_file(img);
}
img = load_file("fname");
break;