0

The following is a recursive function that is supposed to turn an integer into a string

char* int_to_word(int word_int){
    static char new[2];
    char alphabet[26]={"abcdefghijklmnopqrstuvwxyz"};
    new[0]=alphabet[word_int%27-1];
    //new[1]='\0';
    if(word_int/27==0){
        return new;
    }
    static char *word;
    strcpy(word,strcat(int_to_word(word_int/27),new));
    return word;
}

I'm getting a segmentation fault with the line strcpy(word,strcat(int_to_word(word_int/27),new)); when word_int > 26. To my knowledge, there's no reason it shouldn't work. My best guess is that I somehow neeed to allocate word before copying into it, but changing the initializer to static char *word=(*char)malloc(100) did not help.

Ben R.
  • 7
  • 2
  • What memory is `*word` pointing to? – peeebeee Sep 20 '19 at 22:31
  • 2
    You never initialized `word`, you need to use `malloc()` to allocate memory for it. – Barmar Sep 20 '19 at 22:32
  • 2
    Using static variables with a recursive function isn't going to work. You'll end up trying to copy between the same strings. – Barmar Sep 20 '19 at 22:34
  • 1
    It seems like you're trying to get around the fact that you can't return a local array, by using static variables instead. But that causes a new problem: Every time you call the function, you'll overwrite the array that you returned from a different call. – Barmar Sep 20 '19 at 22:37
  • This `char alphabet[26]={"abcdefghijklmnopqrstuvwxyz"};` is not what you want, is an `**char` you probably want `char foo[] = "bar";` – geckos Sep 20 '19 at 22:38
  • Maybe `% 26`??????? – wildplasser Sep 20 '19 at 22:39
  • You return `word`, which is a pointer to char defined in the previous line but not initialised and not malloced for. Then you ask strcpy to write to the memory referenced by that non-initialised pointer. Be grateful for your nice computer to help you with a segfault. https://en.cppreference.com/w/c/string/byte/strcpy – Yunnosch Sep 21 '19 at 09:15

0 Answers0