Search code examples
crecursionsegmentation-faulttail-recursionc89

Segmentation fault error in tail recursive function?


I am writing a function in C that converts a number to a different base such as octal, binary, hexadecimal, etc. We are required to write it recursively and the function must return a char *. However, I am getting a segmentation fault error on this snip pend of code. I am also not sure if the conversion is working properly because I cannot get past this error. I am brand new to C so I apologize if there is anything I am obviously missing.

#include <stdio.h>

char *convertToBaseOut(short int num, int base);

int main()
{
    printf("%s", convertToBaseOut(256, 8));
    return 0;
}

char *convertToBaseOut(short int num, int base) {
    if (num == 0) {
        return '0';
    }
    return convertToBaseOut(num/base, base) + (num % base);
}

Segmentation fault

...Program finished with exit code 139


Solution

  • In C you can't use + to concatenate strings.

    Here you have simple recursive function:

    size_t tostring(char *str, unsigned num, unsigned base)
    {
        static const char digits[] = "0123456789ABCDEF";
    
        size_t pos;
        if(!num)
        {
            return 0;
        }
        else
        {
            pos = tostring(str, num / base, base);
            str[pos++] = digits[num % base];
            str[pos] = 0;
        }
        return pos;
    }
    
    int main()
    {
    
        char str[20];
        printf("%u\n" , tostring(str,0xabcd, 2));
        printf("%s\n", str);
    
        return 0;
    }
    

    It reruens length of the string as well.