0

In the following code, what am I doing wrong? I run the code in eclipse and using MinGW C compiler. When I run it eclipse stops responding. When I debug the code, it breaks on the line

*start = *end;

I verified the value of *start and *end in debug mode and none is null.

void func1(char *str)
{
    char *end, *start;
    end = start = str;
    char tmp;

    if (str)
    {
        while (*end)
            ++end;
        --end;

        while (start < end) 
        {
            tmp = *start;
            *start = *end;
            *end = tmp;

            start++;
            end--;
        }
    }
}

Any tips/ideas?

Big Ali
  • 217
  • 1
  • 8
  • 2
    Could be a lot of things, maybe you are using a string literal? Providing a [SSCCE](http://www.sscce.org/) would allow us to help you better. – Shafik Yaghmour Aug 07 '13 at 19:10
  • 5
    It's almost certainly due to passing in a read-only string literal, but you also have another problem: if the string is the empty string `""`, then the decrement of `--end` puts `end` before the start of the string, and that's technically Undefined Behavior, though that's highly unlikely to cause any practical problems. – Adam Rosenfield Aug 07 '13 at 19:15
  • How do you know that `--end` is legal? – Kerrek SB Aug 07 '13 at 19:22
  • Works for me. What are you passing to it? – Jiminion Aug 07 '13 at 19:23
  • I'm passing "Hello World". When the code reaches that line, *start has 'H' and *end has 'd' in debug window. and "Hello World" is also defined as char pointer in the main function that calls func1. – Big Ali Aug 07 '13 at 19:43

1 Answers1

3

So according to your feedback your are passing a string literal, "Hello World" to func1, modifying a string literal is undefined behavior, you could alternatively use something like this and it will work:

char arr1[] = "hello world" ;
func1(arr1) ;

Although as Adam and Kerrek pointed out you need to add more error checking to you code but this should fix your immediate problem.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740