Reputation: 1
I've been trying to manipulate the elements of the string "Hello World!" found in the main function. My goal is to capitalize the lowercase letters of "Hello World!" inside the function "capitalize" but it doesn't let me. I tried returning the string without manipulating any elements of it and it worked fine but once I included the part of the code that converts a lower case character to an uppercase one, a runtime error appears saying "Thread 1: EXC_BAD_ACCESS (code=2, address=0x100000fa9). What is not allowing me to manipulate the character array and what should I do to fix it?
char *capitalize(char *str)
{
int i;
for(i = 0; i < 4; i++)
if(str[i] >= 'a' && str[i] <= 'z')
str[i] -= 32; //I receive an error hear saying
//Thread 1: EXC_BAD_ACCESS (code=2, address=0x100000fa9)
return str;
}
int main()
{
char string[40];
printf("\n%s\n", strcpy(string, capitalize("abcd")));
return 0;
}
FOR REFERENCE I HAVE INCLUDED THE SPECIFIC PROBLEM IN THE TEXTBOOK:
Problem 3.4. Implement char *Capitalize(char *str); which will capital- ize all lower case letters in the string. The functions returns the pointer to the first byte of the modified string. For example, the function call strcpy(string, Capitalize("Hello World!")); will copy "HELLO WORLD!" as the value of vari- able string.
Upvotes: 0
Views: 96
Reputation: 409364
The problem is that capitalize("abcd")
attempt to modify a literal string.
All literal strings are in effect read-only and can't be modified. Attempting to modify a literal string leads to undefined behavior.
You need to use a non-constant array and pass a pointer to its first element for it to work:
char string[40] = "abcd";
printf("\n%s\n", capitalize(string));
On another note, your code is using magic numbers which is bad, as well as your code only working with a specific encoding (ASCII).
To make your program portable please use the toupper
function:
char *capitalize(char *str)
{
for(size_t i = 0; str[i] != '\0'; i++)
str[i] = toupper(str[i]);
return str;
}
I have also changed the loop condition to check for the string null-terminator.
Upvotes: 1