Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda