Issue
I have a function that specifies a const parameter to indicate to the caller that it won't be modfied:
int func1(const char *some_string)
{
// Do something non-destructive with some_string
}
I pass a non-const variable as an argument to func1
:
int func2(void)
{
char *my_string = "my text";
func1(my_string);
}
gcc reports:
warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
What is the correct way to deal with this situation? Creating a const copy of my_string
seems a bit much, but simply casting seems like burying the warning.
Solution
The issue you're having stems from your main
function.
When you declare char *my_string = "my text";
,you are creating a non-const pointer to a string literal. By design, string literals such as "my text"
are immutable, and therefore const in the language. (In practice, the compilers usually put the string literals into a specific section of the executable which contains read-only memory, so attempting to modify the literal using the non-const pointer can lead to a segfault.)
By declaring a non-const pointer to the string literal, you end up with a pointer which you could use to modify the immutable string literal, which is considered undefined behavior in C.
See this question for more information.
The easiest way to solve this is to simply change char *my_string
into const char *my_string
.
Answered By - Andrei Bârsan