0

I'm trying to implement tolower(char *) function, but I get access violation error. I came to know that this is because to compiler stores string literals in a read-only memory. Is this true? Here's some code:

char* strToLower(char *str)
{
    if(str == nullptr)
        return nullptr;

    size_t len = strlen(str);
    if(len <= 0)
        return nullptr;

    for(size_t i = 0; i < len; i++)
        *(str+i) = (char)tolower(*(str+i));//access violation error

    return str;
}

int main()
{
    char *str = "ThIs Is A StRiNgGGG";

    cout << strToLower(str) << endl;

    system("pause");
    return 0;
}

If this is true, how am I supposed to implement such function?

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
McLovin
  • 3,295
  • 7
  • 32
  • 67

1 Answers1

3

Yes, it's true. You cannot modify a string literal. In fact, if your compiler were not from 1922 it would have prevented you from even obtaining a non-const pointer to a string literal in the first place.

You didn't state your goals, so when you ask "how am I supposed to implement such function" it's not really clear what you want to do. But you can make a copy of the string literal to get your own string, then modify that as you please:

// Initialises an array that belongs to you, by copying from a string literal
char str[] = "ThIs Is A StRiNgGGG";

// Obtains a pointer to a string literal; you may not modify the data it points to
const char* str = "ThIs Is A StRiNgGGG";

// Ancient syntax; not even legal any more, because it leads to bugs like yours
char* str = "ThIs Is A StRiNgGGG";

Of course, since this is C++, you should not be using C-strings in the first place:

std::string str("ThIs Is A StRiNgGGG");
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I made the string literal non-const so I thought I can modify it. So do you claim that a function cannot take a `char*` and modify every char as it wishes? – McLovin Mar 22 '15 at 15:12
  • @Pilpel: If that `char*` points to a string literal, then, no, it can't. As I stated clearly in my answer. _String literals cannot be modified_. Heck, you said that yourself in your question!! – Lightness Races in Orbit Mar 22 '15 at 15:16
  • I see. So I guess I should stick to std strings although I always have this annoying feeling when I use them because (in my mind) they seem to take more space and make my application slower than using c-strings. – McLovin Mar 22 '15 at 15:19
  • 1
    @Pilpel: Which is false (modulo dynamic allocation)! I understand the intuition, though. "Objects" always _feel_ heavier, even though they're not. – Lightness Races in Orbit Mar 22 '15 at 16:08