0

I have the following code which its main purpose is reverse the characters of a string. So, for example, the string I love cats would be converted to stac evol I.

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

void reverseString(char *str)
{
   int size = strlen(str);
   char *end = str + size - 1;
   char tmp;

   while (end > str) {
     tmp = *str;
     *str = *end;
     *end = tmp;
     end--;
     str++;
   }
}

int main()
{
  char *str = "Y U SEGMENTATION FAULT?";
  reverseString(str);

}

When I run this, I get a segmentation fault, and I fail to see why. Also, another question I have is the time complexity (Big O) of this function. I believe it should be O(n/2), since I am not going through all the array but just the half of it. Am I right?

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

1

You are trying to modify a character literal, a string in read only data segment. Make a copy/duplicate of it on the heap with strdup, for example:

char *str = strdup("It's OK now");

Or make it a local array (place the string on the stack):

char[] str = "It's OK now";
piokuc
  • 25,594
  • 11
  • 72
  • 102
  • But according to http://stackoverflow.com/questions/8732325/how-to-declare-strings-in-c -- If I declare my string with a pointer, I can modify it, right? – Hommer Smith Feb 12 '13 at 10:43
  • No, you can declare your string as a local array, as hmjd suggested, that will be a different story. – piokuc Feb 12 '13 at 10:44
  • @HommerSmith One of the differences between `char *foo = "bar";` and `char foo[] = "bar";` is the method of initialisation. The former converts the read only array to a pointer and stores the pointer. The latter *copies* the read only array into a new modifiable array. – autistic Feb 12 '13 at 11:11