Search code examples
cstringreverse

String reverse - segfault


This is not a repeated qn. A new method is used to reverse a string from already asked qn.

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

char *revStr(char *str)
{
    int i = 0, j = 0, count = 0;
    char *retStr;

    while(str[count] != '\0')
    {
        printf("first %c for %d\n", str[count], count);
        count++;
    }

    count--;

    for (i = count, j = 0; i >= 0, j<=count; i--, j++)
    {
        //printf("sec %c for %d\n", str[i], i);
        retStr[i] = str[j];
        printf("thrd %c for %d\n", retStr[i], i);
    }
    return retStr;
}

int main()
{
    char *str = NULL, *revStr2 = NULL;
    str = (char *) malloc (5);
    strcpy(str, "hello");
    printf("\n%s\n", str);
    printf("\n%s\n", revStr(str));
}

gives me the output as O/P:


hello
first h for 0
first e for 1
first l for 2
first l for 3
first o for 4
thrd h for 4
thrd e for 3
thrd l for 2
thrd l for 1
thrd o for 0
olleh

Segmentation fault


Can someone pls help how string reveral can be acheived using this method. Thanks, Preethi


Solution

  • You need to assign memory to retstr like below

    char *revStr(char *str)
    {
        int i = 0, j = 0, count = 0;
        while(str[count] != '\0')
        {
            printf("first %c for %d\n", str[count], count);
            count++;
        }
     char *retStr = (char*)malloc(count);
        count--;
    
        for (i = count, j = 0; i >= 0, j<=count; i--, j++)
        {
            //printf("sec %c for %d\n", str[i], i);
            retStr[i] = str[j];
            printf("thrd %c for %d\n", retStr[i], i);
        }
        return retStr;
    }