Reputation: 19
I'm trying to make a function that goes through a linked list and finds all strings that contain a substring that the user inputs.
The problem is that its case sensitive and I need it to not be. My idea was to make everything lowercase while going through the list. And wrote something that should work... I think... but doesn't
char *lowerCase(char* strToLower){
char *lowCase;
strcpy(lowCase, strToLower);
for(int i = 0; lowCase[i]; i++){
lowCase[i] = tolower(lowCase[i]);
}
return lowCase;
}
printf("%s", lowerCase("Name"));
Now, what ideally should pop up is "name", but I instead get nothing.
I get Process returned -1073741819 (0xC0000005), which I think is an error related to pointers or memory? I don't really know because build log doesn't tell me anything.
Any help is appreciated <3
Upvotes: 0
Views: 44
Reputation: 5232
The Problem is that you use strcpy
wrong. Please refer to the manpage: https://linux.die.net/man/3/strcpy
You need to actually allocate a buffer for the copied string. You right now just copy it to a random memory location (as lowCase
is not initialized).
You need to so:
char *lowerCase(char* strToLower){
char *lowCase = (char *)malloc(strlen(strToLower) + 1); // +1 because of terminator
strcpy(lowCase, strToLower);
for(int i = 0; lowCase[i]; i++){
lowCase[i] = tolower(lowCase[i]);
}
return lowCase;
}
and it should work. But beware: As lowCase
was allocated, you also need to free
it after use, otherwise you have a memory leak.
Upvotes: 2