I am currently using exercism, to improve my programming skills. The code works fine in my IDE, but causes an error message on the website. What did I do wrong and how would you improve my code? Thx in advance :)
make: *** [makefile:22: test] Segmentation fault (core dumped)
#include "isogram.h"
#include <string.h>
#include <ctype.h>
bool is_isogram(const char phrase[]) {
int length = strlen(phrase);
char temp[length];
for (int i = 0; i < length; i++)
temp [i] = phrase[i];
temp[length] = '\0';
for(int i = 0; temp[i]; i++){
temp[i] = tolower(temp[i]);
}
for(int i = 0; i < length; i++){
for(int j = i+1; j < length;j++) {
if (temp[i] == temp[j] && temp[i] != ' ' && temp[i] != '-')
return false;
}
}
return true;
}
int main(void) {
char phrase[] = "lumberjacks";
if (is_isogram(phrase))
printf("true");
else
printf("false");
return 0;
}
I asked ChatGPT and it suggested the temp[length] = '\0'; line, but this doesn't fix the issue.
For starters using the variable length array
is unsafe and redundant. Pay attention to that the return type of the function
strlenis the unsigned typesize_tnot the signed typeint.Also calling the function
strlenis redundant. You can scan a string based on the fact that it is terminated by the terminating zero character'\0'.You defined an array that does not have a room for the terminating zero character
'\0'. As a result this assignmentinvokes undefined behavior.
To convert all characters of the variable length array before checking whether the string is isogram
is inefficient.
Words in a phrase can be separated not only by the space character
' 'but also by the tab character'\t'. Also you should exclude punctuations.I would write the function the following way as shown in the demonstration program below.
The program output is