Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

robust string reverse

Tags:

c

string

swap

I am trying to code a trival interview question of reversing a string.

This is my code:

#include <string.h>

char* rev( char* str)
{
    int i,j,l;

    l = strlen(str);

    for(i=0,j=l-1; i<l/2 ; i++, j--)
    {
        str[i] = (str[i] + str[j]);
        str[j] = str[i] - str[j];
        str[j] = str[i] - str[j];
    }

    return str;
}

int main()
{
    char *str = " hello";
    printf("\nthe reverse is %s ...", rev(str));

    return 1;
}

Basically, this one gives a segmentation fault.

I have following questions:

  1. I get segmentation fault probably because, the characters add up to something not defined in ascii and hence I cannot store them back as characters, I am using www.codepad.org [I wonder if it supports just ascii !!] . Is my understanding correct or there is something else to it.

  2. How do I correct the problem , for the same platform [I mean swapping in place for codepad.org]

  3. Here I have to use an additional integer l to calculate length. So to save a single char space by swapping in place .. I am using an extra int !!! .. just to impress the inteviewer :) ... Is this approach eve worth it !!!

  4. This one is for those who are interested in writing unit tests/API tests . I want to have a robust implementation so what can be possible test cases. I assume that if interviewer asks such a simple question .. he definitely wants some very roboust implementation and test cases. Few that I thought off:

    • passing empty strings passing integer

    • strings passing integer array instead of char array.

    • very long string ,

    • single char string string of special chars.

Any advise/suggestions would be helpful.

like image 443
p1. Avatar asked Feb 25 '26 00:02

p1.


2 Answers

This line:

char *str = " hello";

Probably points to read-only memory. Try this:

char str[] = " hello";

(You have some other bugs too, but this change will fix your segfault).

like image 93
Carl Norum Avatar answered Feb 28 '26 05:02

Carl Norum


Use a temporary variable rather than your approach for the swap. The compiler will probably use a register for the temporary variable due to optimizations.'

Either way, you implemented the swap algorithm wrong. It should be

str[i] = str[i] + str[j];
str[j] = str[i] - str[j];
str[i] = str[i] - str[j];
like image 24
alternative Avatar answered Feb 28 '26 04:02

alternative