I am trying to write a simple code to solve a morse code. But I am getting segmentation fault (core dumped) although I use malloc to allocate memory. I don't understand why did I get segmentation fault. How can I solve this problem?
My code is
const char *morse[55] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", ".-.-.-", "--..--", "..--..", ".----.", "-.-.--", "-..-.", "-.--.", "-.--.-", ".-...", "---...", "-.-.-.", "-...-", ".-.-.", "-....-", "..--.-", ".-..-.", "...-..-", ".--.-.", "...---..."};
const char *ascii[55] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ",", "?", "'", "!", "/", "(", ")", "&", ":", ";", "=", "+", "-", "_", "\"", "$", "@", "SOS"};
char *decode_morse(const char* morse_code)
{
int c1;
char *str;
char *result;
int c2;
int i;
int j;
i = 0;
j = 0;
c1 = 0;
result = (char *)malloc(sizeof(char) * strlen(morse_code));
str = (char *)malloc(9 * sizeof(char) +1);
while (morse_code[c1] != '\0')
{
while (morse_code[c1] == '.' || morse_code[c1] == '-')
{
c2 = 0;
while (morse_code[c1] != ' ')
{
str[c2] = morse_code[c1];
c1++;
c2++;
}
while (strcmp(str,morse[i]) != 0)
{
i++;
if (strcmp(str,morse[i]) == 0)
result[j++] = ascii[i][0];
}
}
c1++;
result[j++] = ' ';
}
return (result);
}
int main()
{
printf("%s\n", decode_morse(".... . -.-- .--- ..- -.. ."));
}