Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Switch case statement doesn't loop

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');
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The reason the program exits is it has undefined behavior:

  • load_file("fname"); may load the image file, but no side effect occurs on img
  • free(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;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!