Correct. Strings provided as string-literals are read-only. You will need to copy the string to mutable memory first:
char* s_readonly = "foobar";
size_t s_length = strlen( s_readonly );
char* s_mutable = malloc( s_length + 1 );
assert( s_mutable );
errno_t err = strcopy_s( s_mutable, s_length, s_readonly );
assert( err == 0 );
to_lower_case( s_mutable );
puts( s_mutable );
free( s_mutable );
- My code performs an explicit copy to the heap. This code could be made simpler by assigning the string literal to a
char[n]-type. This has the advantage of allowing static sizeof() to work which is faster O(1) than strlen which is O(n).
printf("%s\n", s) can be replaced with puts which is faster as there's no format-string to parse.
- I use
strcopy_s over the insecure strcopy. Always check the returned error code!
- And always call
free after malloc. If you're dealing with short strings you could use alloca instead which is faster and doesn't require the use of free.
Alternatively, just this:
char s_mutable[] = "foobar";
to_lower_case( s_mutable );
puts( s_mutable );
The advantage here (besides terseness) is that s_mutable is mutable right away, and it means that sizeof( s_mutable ) == 12.