Ilo Ilo - 1 year ago 102
C Question

tolower for C-style strings

I'm trying to perform case insensitive strcmp on two C-style strings.

I have a function to convert C-style strings to lowercase.

char* ToLowerCase(const char* str)
char buffer[strlen(str)];
for (int i=0; i<strlen(str); ++i)
buffer[i] = char(tolower(str[i]));
return buffer;

One string comes from function char* GetMyString(int i), and the second is in array of C-style strings char* myStrings[5].

So assuming that both GetMyString(0) and myString[0] both return "TEXT"

strcmp(ToLowerCase(GetMyString(0)), ToLowerCase(myStrings[0]));

compares strings like "mytextxaogs5atx" "mytextxabs5atx" (some random text gets added...)


strcmp(GetMyString(0), myStrings[0]);

works just fine, so that I assume there's nothing to do with the null termination as some of you might think.

What is wrong with my code? Did I miss something? I've looked at many questions about tolower but none of them were able to help with my problem.

Answer Source
return buffer;

You return a pointer to a variable that's local to ToLowerCase, the pointer will point to garbage after the call, resulting in undefined behaviour when trying to dereference the pointer. Either change the str itself or dynamically allocate the memory for buffer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download