underdog_eagle
underdog_eagle

Reputation: 25

Generating absurd output

I wrote the following code but it is generating absurd output values. I can't figure out what's wrong in the code.

#include <stdio.h>

int main(void)
{
    int t, n, i, count;
    scanf("%d", &t);

    while(t--)
    {
        scanf("%d", &n);
        long long a[n], limit;

        for(i = 1; i <= n; i++)
            scanf("%lld", &a[i]);

        count = 1;
        limit = a[1];
        for(i = 2; i <= n; i++)
        {
            if(a[i] < limit)
            {
                count++;
                limit = a[i];
            }
        }

        printf("%lld\n", count);
    }

    return 0;
}

INPUT :-

3
1
10
3
8 3 6
5
4 5 1 2 3

OUTPUT :-

-4621320042389176319
4615368115365085186
-4621320334446952446

Please give the explanation for whatever problem with my code.

Upvotes: 0

Views: 86

Answers (4)

alk
alk

Reputation: 70931

You are using the wrong length modifier here:

 printf("%lld\n", count);

Doing so invokes undefined behaviour, so anything could be printed — anything could happen.

To print an int (which count is) just use d without any length modifiers.

 printf("%d\n", count);

(or define count to be a long long int, which is what lld expects).

Upvotes: 0

Andrew Henle
Andrew Henle

Reputation: 1

Given

int count;

this code

printf("%lld\n", count);

is undefined behavior.

Per the C Standard, the format specifier "ll" is for long long int types:

ll (ell-ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long long int or unsigned long long int argument; or that a following n conversion specifier applies to a pointer to a long long int argument.

And

If a conversion specification is invalid, the behavior is undefined.

Upvotes: 1

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

I cannot reproduce the garbage output, but I see two occurrences of UB in your code, caused by accessing the a array out of bounds:

for(i = 1; i <= n; i++)
   scanf("%lld", &a[i]);

...and...

for(i = 2; i <= n; i++)
{         
    if(a[i] < limit)
    {
            count++;
            limit = a[i];
    }
}

In the first case you're iterating over the [1, n] range (where n is inclusive). In the second case you're iterating over the [2, n] range (where n is inclusive).

But your a array has n elements, so its range is [0, n), with n exclusive.

Upvotes: 2

Ingo Leonhardt
Ingo Leonhardt

Reputation: 9894

There are at least two issues: First, in C array indexes start with 0, not 1. So it must be

    for(i = 0; i < n; i++)
        scanf("%lld", &a[i]);

    count = 1;
    limit = a[0];
    for(i = 1; i < n; i++)
    {
        if(a[i] < limit)
        {
            count++;
            limit = a[i];
        }
    }

Second, you call printf("%lld\n", count); but count is an 'ordinary int', so it should be printf("%d\n", count);

Upvotes: 4

Related Questions