I got 2 functions:
– stringCopy() which copy the parameter strToCopy into another string dynamically allocated applying a sanitize (see 2nd function)
– _sanitized() which returns a dynamically allocated uppercased version of the parameter and removing non-letters char (such as numeric values & spaces).
Considering the following, I got an EXC_BAD_ACCESS because of k growing too much.
char* _sanitized(const char* str)
{
char* uppercasedStr = malloc(sizeof str);
int k = 0; // Index de parcours de la chaîne originale
int i = k; // Index dans la nouvelle chaîne
char evaluatedChar;
while ( (evaluatedChar = str[k]) != '\0')
{
if ('A' <= evaluatedChar && evaluatedChar <= 'Z')
{
uppercasedStr[i] = evaluatedChar;
i++;
}
else if ('a' <= evaluatedChar && evaluatedChar <= 'z')
{
uppercasedStr[i] = evaluatedChar-32;
i++;
}
k++;
}
i++;
uppercasedStr[i] = '\0';
return uppercasedStr;
}
char* stringCopy(char* strToCopy)
{
char* uppercaseStr = _sanitized(strToCopy);
char* copiedStr = malloc(sizeof uppercaseStr);
int k = 0;
while (uppercaseStr[k] != '\0')
{
copiedStr[k] = uppercaseStr[k];
k++;
}
k++;
copiedStr[k] = '\0';
free(uppercaseStr);
return copiedStr;
}
I also noticed that when I copy char from uppercaseStr into copiedStr it modifies uppercaseStr in the same time which cause the overflow…
The error I see is here:
You can’t use
sizeof()to get the length of a string. You need to usestrlen():Here’s the other occurrence of the same mistake:
should be:
sizeof(str)only gives you the size of acharpointer, not the length of the entire c-string.Also note that I omitted the
sizeof(char). This is becausesizeof(char)is defined to be 1 in C. Therefore it is not needed.