Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda