Why this program is crashing?

What yo actually do is called “undefined behavior”.

You allocate 4 bytes and then store into that buffer integers. It works fine for the first integer (or maybe two if sizeof(int)==2 on your machine) but for the next integer the behavior becomes undefined. It may segfault immediately and it may take more similar stores until you crash. The number of inputs ‘5’ here doesn’t mean anything, it may behave differently on different machines and with different compilation flags.

According to what I see (or assume from the code), you want to accept inputs until you get “42”. So actually you don’t have to store the input values. Here is your code without the useless stuff:

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

int main()
{
    int in;

    for(;;)
    {
        scanf("%d",&in);
        printf("%d\n", in); // adding this line because it was explained to
                            // me that the input values should be printed and 
                            //it is something I couldn't understand from the original code.
        if(in == 42)
        {
            break;
        }
    }

    return 0;
}

Leave a Comment