1

Possible Duplicate:
Is it possible to modify a string of char in C?

I have a function to convert a char* to lower case. This is the function:

void toLower(char* word, int length)
{
    int i;

    for(i = 0; i < length; i++) {
        // this I can do
        // printf("%c", tolower(word[i]));

        // this throws segfault
        word[i] = tolower(word[i]);
    }
}

When I call it like this from main, it throws a segfault error:

char* needle = "foobar";
toLower(needle, strlen(needle));

I'm certain the issue is in the assignment here:

word[i] = tolower(word[i]);

But I can't seem to figure out the corect way to do it. I tried passing it as char**, or doing *(word+i), but all cause the same issue.

Community
  • 1
  • 1
Ayush
  • 41,754
  • 51
  • 164
  • 239

4 Answers4

6

You are attempting to change the constant string "foobar". Try:

char needle[] = "foobar";

This will create an array containing the string "foobar" (the compiler arranges to copy the data from the constant string "foobar" to your array needle where you can modify it).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
2

You cannot modify a string literal. You can create a dynamic string:

char *str = strdup(needle);
toLower(str, strlen(str));
/* ... */
free(str);
perreal
  • 94,503
  • 21
  • 155
  • 181
1

The problem is that char *needle = "foobar" is a string literal -- it's a const char. In order the compiler to generate a writable string, use

char needle[] = "foobar";

instead.

1

Changing a string literal is not possible.
You can do this

 word[i] = tolower(word[i]);

only in two cases, either

char needle[] = "foobar";

or
first create memory for char * using malloc and then assign a string to it, like this

char * str = (char *) malloc(size0f(char)*10);
strcpy(str,"foobar");

Now you can use this

neel
  • 8,399
  • 7
  • 36
  • 50