I solved the codewars training as below. I'm getting an error message, what's wrong in the code? I don't know what is going on, so please let me know. But it is capitalizing every word!
I passed: 111 tests Failed: 1 Errors: 1 Exit Code: 1
**Test Crashed Caught unexpected signal: SIGSEGV (11). Invalid memory access. **
It is a Jaden Casing Strings (It is capitalizing every word!)
char *to_jaden_case (char *jaden_case, const char *string){
// write to jaden_case and return it
int i = 0;
if(*(string) <= 'z' && *(string) >= 'a'){
*(jaden_case) = *(string) - 32;
}
else{
*(jaden_case) = *(string);
}
for(i = 1;*(string + i) != '\0'; i++){
if( *(string + i - 1) == ' '){
if(*(string + i) <= 'z' && *(string + i) >= 'a'){
*(jaden_case + i) = *(string + i) - 32;
}
else{
*(jaden_case + i) = *(string + i);
}
}
else{
*(jaden_case + i) = *(string + i);
}
}
*(jaden_case + i) = '\0';
return jaden_case;
}
The first test case is the empty string:
Test(tests_suite, fixed_tests)
{
sample_test(
"",
""
);
/* ... */
In that case, the following
for(i = 1;*(string + i) != '\0'; i++)
will cause Undefined Behaviour when accessing an invalid index via string[1]
.
Consider using the functions found in <ctype.h>
, such as isspace
and especially toupper
to solve this.
Generally, consider using the syntax foo[n]
, instead of *(foo + n)
.
That said, the minimal change required for your code is to place the for
loop inside a guarding if
that checks if the string is at least one character long.
if (*string) {
for (/* ... */) {
/* ... */
}
I might suggest doing this, and then having a look at the more well received solutions.