facetoe
facetoe

Reputation: 729

C loop throws error unless printf() included?

I have a function in C:

int concanatedProduct(int n, int x, int size)
{
    char numberString[10];
    long arr[size];
    int cnt = 0;

    long product = 0;
    int digit = n;
    while (digit!=0) {

        product = x * (digit % 10); // Multiply by last digit
        arr[cnt] = product; // add to array
        cnt++; // increment count
        digit /= 10; // chop off last dig

    }

    for (int i=size-1; i>=0; i--) { // reverse the number to make it the right way
        //printf("%ld", arr[i]);
        sprintf(numberString, "%s%ld",numberString, arr[i]);
    }

        return atoi(numberString);
}

It works fine when I use it outside a loop. However when I try and put it in a for loop it throws SIGBART error unless I include printf.

This works:

for (int i=1; i<10; i++) {
        x = concanatedProduct(12, i, 2);
        printf("%d\n", x);
    }

This throws an error:

for (int i=1; i<10; i++) {
        x = concanatedProduct(12, i, 2);
    }

What on earth is going on? It's got me completely stumped.

Upvotes: 0

Views: 136

Answers (2)

Paul Hankin
Paul Hankin

Reputation: 58271

Section 7.19.6.6 of the C99 standard says:

The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

The italicised sentence means that even if numberString is initialised, the line:

sprintf(numberString, "%s%ld", numberString, arr[i]);

has undefined behavior.

Upvotes: 1

Musa
Musa

Reputation: 97672

In your first call to sprintf numberString is not initialized, resulting in such behaviour.

Upvotes: 3

Related Questions