I'm kind of struggling with some of the basics for C. I tried to compile this program and it came up with a Signal 11 Error. I know this is to do with memory allocation, but I'm not sure how to use malloc()
correctly to make this work. Can someone help?
{
char *string = "Lol";
convert_lower(string);
printf("%s\n", string);
return 0;
}
char *convert_lower(char *word) {
for ( ; *word; ++word) *word = tolower((char)*word); // J.F. Sebastian
return word;
}
You are giving
convert_lower()
a pointer to a string literal, so it will try to modify read-only memory. That is why you get the runtime error.You need to make a writable copy of the string literal's data before you can then modify it, eg:
Which can be simplified using
strdup()
instead, which will handle the allocation and copy for you:And then, you can simplify this further by just not allocating any dynamic memory at all: