Question

reverser() reverses a cstring (not in place). 99% of the time it works but some input corrupts it for example it appears if aStr2[] is assigned a string made up of the same character it will have an error.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* reverser(const char *str);

int main()
{
    char aStr[] = "aaa";
    char aStr2[] = "cccccc";
    printf("%s %s", aStr, aStr2);
    char* tmp = reverser(aStr2);//tmp now has garbage
    printf("\n%s", tmp);
    printf(" %s", aStr2);
    return 0;
}


char* reverser(const char *str)
{
    char* revStr = (char*)malloc(strlen(str));
    int i;
    for(i = strlen(str)-1; i >= 0; i--)
{
        revStr[strlen(str)-1-i] = str[i];
}
    return revStr;
}

Gives

aaa cccccc
cccccc9 cccccc
Process returned 0 (0x0)   execution time : 0.068 s
Press any key to continue

Notice the 9 that shouldn't be there.

Was it helpful?

Solution

Change this malloc to strlen(str) + 1 , plus 1 for '\0'

char* revStr = (char*)malloc(strlen(str) + 1);

and after the for loop

revStr[strlen(str)+1] = '\0';

OTHER TIPS

Your problem is that you don't put the string terminator in your reversed string. All strings in C are actually one extra character that isn't reported by strlen, and that is the character '\0' (or plain and simple, a zero). This tells all C functions when the string ends.

Therefore you need to allocate space for this extra terminator character in your malloc call, and add it after the last character in the string.

There are also a couple of other problems with your code, the first is that you should not cast the return of malloc (or any other function returning void *). Another that you have a memory leak in that you do not free the memory you allocate. This last point doesn't matter in a small program like the one you have here, but will be an issue in larger and longer running programs.

You haven't null-terminated your reversed string. You need to set the final index of revStr[] to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top