-1

I get segmentation fault whenever i try to run this. Have no idea why. The logic seems to be correct, its probably something with function calls. Debugger says something about stack but i have no idea how to interpretate this.

char* rev_string(char* t)
{
    int i;
    int j;
    i = j = 0;
    char tmp;
    while(t[i] != '\0')
        i++;
    while(i > j)
    {
        tmp = t[i];
        t[i] = t[j];
        t[j] = tmp;
        i--;
        j++;
    }
    return t;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Jan Chabik
  • 37
  • 2
  • what is the 'something' that it says? – pm100 Jan 15 '18 at 21:31
  • did you actually try stepping through with the debugger? Watch i and j – pm100 Jan 15 '18 at 21:32
  • 3
    When the first loop ends, `t[i]` _will_ be equal to zero, so, even if the process succeeds, you'll have a null-terminator at the beginning. – ForceBru Jan 15 '18 at 21:33
  • You need to show a [MCVE]. – interjay Jan 15 '18 at 21:34
  • And after I got through with adding the boilerplate code this example needs to actually *run*... I -1'ed. – DevSolar Jan 15 '18 at 21:34
  • 1
    My guess is you are calling this function on a string literal, but we will never know if you don't show how you're calling it. Also, how about telling us what the debugger actually showed instead of "something about stack"? – interjay Jan 15 '18 at 21:38
  • "Program received signal SIGSEGV. Stack Trace is available in the call stack tab" then it points to line 25 (t[i] = t[j]) then again "Program received..." and then it crashes – Jan Chabik Jan 15 '18 at 21:49
  • char* text = "sampletext"; char* newtext = rev_string(text); – Jan Chabik Jan 15 '18 at 21:55
  • @JanChabik, well, that's the problem: it's impossible to reverse a string literal because it's impossible to modify it. You should either copy it with `strdup` or allocate memory like `char text[] = "stuff";`. – ForceBru Jan 16 '18 at 08:39

1 Answers1

0

I believe that you are swapping the first character with the null terminating character at the end of the string, causing the string to be of length 0 since the first character is \0. You need to move your j marker back by one once you found \0.

char* rev_string(char* t)
{
    int i;
    int j;
    i = j = 0;
    char tmp;
    while(t[i] != '\0')
        i++;
    i--;
    while(i > j)
    {
        tmp = t[i];
        t[i] = t[j];
        t[j] = tmp;
        i--;
        j++;
    }
    return t;
}
Devan Buggay
  • 2,717
  • 4
  • 26
  • 35