You need more space for a string, strlen()
gives you the number of characters, but c strings use an extra character to mark the end of the string, the '\0'
ascii nul
character, so 1 + strlen(otherString)
is always required to copy a string.
You check str
for NULL
after dereferencing it. That doesn't make sense, fist check for NULL
and then call strlen()
.
Using strlen()
that way is not a good idea, because in c the string length is not stored anywhere, calling strlen()
computes the string basically this way
size_t strlen(const char *string)
{
size_t count = 0;
while (*string++ != '\0')
count++;
return count;
}
there you can see how important the terminating '\0'
is, and why you should not call strlen()
in a loop for a string whose length doesn't change.
If you return the address of a local variable, it will not work as you expect, because it wil be deallocated when the function returns, so you need to use dynamic allocation, for that there exists malloc()
which makes it easy to do, so in your case it would be something like this
char *reverseString(char *str)
{
size_t index;
char *test;
size_t length;
if (str == NULL)
return NULL;
length = strlen(str);
test = malloc(1 + length);
if (test == NULL)
return NULL;
/* perform string reversal */
for (index = 0 ; index < length ; index++)
test[index] = str[length - index - 1];
/* add the `nul` terminator */
test[length] = '\0';
/* return the newly allocated and initialized data */
return test;
}