Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast discards qualifiers from pointer target type?

Tags:

c

gcc

-Wcast-qual outputs this warning on stristr()'s return line. What is the problem ?

warning: cast discards qualifiers from pointer target type

char *stristr(const char *string, const char *substring)
{
size_t stringlength = strlen(string);
char *stringlowered = malloc(stringlength + 1);
strcpy(stringlowered, string);
tolower2(stringlowered); // in my source it has a different name, sorry.

char *substringlowered = malloc(strlen(substring) + 1);
strcpy(substringlowered, substring);
tolower2(substringlowered); // in my source it has a different name, sorry.

const char *returnvalue = strstr(stringlowered, substringlowered);
if(returnvalue != NULL)
{
    size_t returnvaluelength = strlen(returnvalue);
    returnvalue = string;
    returnvalue += stringlength - returnvaluelength;
}

free(stringlowered);
free(substringlowered);

return (char *)returnvalue;
}

EDIT :
In glibc 2.15's strstr() source code:

return (char *) haystack_start; // cast to (char *) from const char *
like image 305
Nigel Ridley Avatar asked Apr 16 '12 20:04

Nigel Ridley


2 Answers

You have declared returnvalue as a pointer to a const char, but then you've cast it to a pointer to non-const char. You've discarded the const qualifier, so the compiler complains that you've discarded it!

The solution is either to change the return type of the function, or to find a non-const char to point at. You don't have one in your function, so you could consider changing the argument type if you really need a non-const return type.

like image 65
Oliver Charlesworth Avatar answered Sep 23 '22 20:09

Oliver Charlesworth


You are casting a const char * (let's call it non-modifiable string) to a char * (modifiable string) you discard the const qualifier.

like image 29
MByD Avatar answered Sep 20 '22 20:09

MByD