Search code examples
csleepnested-loops

Function Sleep in C makes the programs prints strange characters


[EDITED]I wrote a program in C and it should print a vertical wave by printing and modifying the vector "riga_disegno" continously.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int riga_disegno[10], i = 0, j = 0, k = 0, length = 0;

    for(i = 0; i < 10; i++) /* Inizializza il vettore */
    {
        riga_disegno[i] = 177;
    }

    printf("Quanti periodi dell'onda vuoi stampare?");
    scanf("%d", &length);

    for(k = 0; k < length; k++)
    {

        for(j = 0; j < 10; j++) /* Assegna ad un componente vettore il disegno dell'onda */
        {
            riga_disegno[j] = 254;

            for(i=0; i < 10; i++)
            {
                putchar(riga_disegno[i]); /* stampa il carattere [i] del vettore*/

            }
            printf("\n");

            riga_disegno[j] = 177; /* Riporta il componente al carattere di base */
        Sleep(100);
        }
        for(j = 9; j >= 0; j--) /* Assegna ad un componente vettore il disegno dell'onda */
        {
            riga_disegno[j] = 254;

            for(i=0; i < 10; i++)
            {
                putchar(riga_disegno[i]);
            }
            printf("\n");

            riga_disegno[j] = 177; /* Riporta il componente al carattere di base */
        Sleep(100);
        }
    }

        return 0;
}

I entered the function Sleep because the execution of the program was too fast, but now, when I compile it prints strange characters near the "wave". Thank you. Sorry for my bad english, I'm italian.


Solution

  • Your code invokes undefined behaviour when you modify riga_disegno beyond its boundaries. You access and modify riga_disegno[-1] and riga_disegno[10]. As explained, undefined behaviour means anything can happen, including expected behaviour.

    In your particular case, you wonder why the behaviour changes when you modify your code by adding function calls Sleep(). A possible explanation is that the compiler generates different code when you modify the source, especially when you invoke external functions. The side effects of modifying memory beyond array boundaries may be different because the array riga_disegno itself or the other local variables i and j may be allocated differently. Without the calls, the side effect might not affect the program's output, leading you to erroneously believe that everything works fine. With the calls, you can see some side effects of this undefined behaviour.

    This is a good illustration for why one should always avoid undefined behaviour. Even if the program seems to function properly, the slightest modification can have catastrophic consequences.