toLower string in C 0xC0000005

0

well I've got this code that I'm trying to get working but no matter what I keep on getting that I am getting 0xC0000005

int main()
{
    if(stringContains("hello", "Hello world", FLAG_CASE_SENSITIVE))
    {
        printf("Works");
    }
    
    printf("%i", stringContains("hello", "Hello world", FLAG_CASE_SENSITIVE));
    return 0;
}

#define FLAG_CASE_INSENSITIVE 0
#define FLAG_CASE_SENSITIVE 1
    
typedef enum { false, true } bool;
    
bool stringContains(char* needle, char* stack, int type);
char* toLower(char* s);
    
bool stringContains(char* needle, char* stack, int type)
{
    if(type == FLAG_CASE_SENSITIVE)
    {
        return (strstr(toLower(stack), toLower(needle)) != 0) ? true : false;
    }
    return (strstr(stack, needle) != 0) ? true : false;
}

char* toLower(char* s) {
    for(char *p=s; *p; p++) *p=tolower(*p);
    return s;
}

I must admit, I am pretty basic when it comes to C

c
asked on Stack Overflow Nov 24, 2020 by Tomislav Tomi Nikolic • edited Nov 24, 2020 by Steve Friedl

1 Answer

1

Try to declare functions which will accept literals as const`:

bool stringContains(const char *needle, const char *stack, int type);

Then you will be warned if the const will be stripped when you call another functions.

https://godbolt.org/z/x4z5vE

You will need to get rid of this problem. Cast will not help as it will only silence the warning but not change anything regarding the strings, so you will need to create the writable copies of the strings.

bool stringContains(const char* needle, const char* stack, int type)
{
    
    if(type == FLAG_CASE_SENSITIVE)
    {
        char *haystack = strdup(stack);
        char *newneedle = strdup(needle);
        char *result = NULL;
        if(haystack && newneedle)
            result = strstr(toLower(haystack), toLower(newneedle));
        free(newneedle);
        free(haystack);
        return !!result;
    }
    return !!strstr(stack, needle);
}

https://godbolt.org/z/Kvdxq3

answered on Stack Overflow Nov 24, 2020 by 0___________

User contributions licensed under CC BY-SA 3.0