Reputation: 65
Hey guys i got an assignment that i cant seem to solve. I get a char* string and i need to make all upper case letters (everything is in ASCII) to lower case using bit operations. I'm adding my code but it keeps crashing.
#include <iostream>
#include <cstring>
using namespace std;
void convertToLower(char* string)
{
for (unsigned int i = 0; i < strlen(string); i++)
{
if (string[i] >= 65 && string[i] <= 90)
{
string[i] |= 32;
}
}
cout << string << endl;
}
int main()
{
convertToLower("Hello");
return 0;
}
Upvotes: 0
Views: 1911
Reputation: 43662
You're trying to modify a string literal i.e. read-only memory: that's the reason for your crash (or undefined behavior to be more precise)
void convertToLower(char* str)
{
for (unsigned int i = 0; i < strlen(str); i++)
{
if (str[i] >= 65 && str[i] <= 90)
{
str[i] |= 32;
}
}
cout << str << endl;
}
int main() {
char arr[] = "STRING";
convertToLower(arr); // Fine
char *readonly = "READONLY";
convertToLower(readonly); // Nope
}
I suppose a recent compiler should also have warned you of this (Wwritable-strings
).
Read more about this issue here: Why are string literals const?
Upvotes: 3
Reputation: 36503
convertToLower("Hello");
"Hello"
is of type const char[]
. Conversion from const char*
to char*
has been illegal since C++11 so your compiler should've told you something about that if you're using a modern one, at least a warning. You can't overwrite read-only memory (const
). Attempting to do so leads to undefined behaviour. Make a copy of it and pass that in:
char copy[] = "Hello";
convertToLower(copy);
Upvotes: 2