Eli
Eli

Reputation: 337

Interesting printf() glitch in C while converting bases

I have the following code in C:

char* getBase(unsigned int a, int base) {
    char buffer[33];

    char digits[] = "0123456789ABCDEF";

    if(base < 2 || base > 16) {
        printf("Invalid base");
        return NULL;
    }

    char* cn = &buffer[sizeof(buffer) - 1];
    *cn = '\0';

    do {
        cn -= 1;
        *cn = digits[a % base];
        a /= base;
    } while(a > 0);

    printf("\n"); //HERE

    return cn;
}

int main() {
    printf("%s", getBase(8, 2));
    return 0;
}

As you can see, it takes a base 10 number, and converts it to something between base 2 and base 16. It works UNLESS I comment out the line marked with //HERE. For some reason, if I don't have that printf statement, it doesn't work. I have no idea why this is happening, any explanations?

Upvotes: 0

Views: 83

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

Undefined behavior could cause some quite weird behavior.

You are returning cn in the function getBase, which is a pointer that points to somewhere in the local automatic array buffer.

To fix the problem, you can make buffer static, or use dynamic allocation.

Upvotes: 1

Related Questions