Search code examples
carraysstringmemory-managementcstring

Need help finding bug, if string input is composed all of same character one output character is corrupt


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.


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';