nverinaud
nverinaud

Reputation: 1300

Dynamic C string (char*) weird behavior

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...

Upvotes: 1

Views: 581

Answers (1)

Mysticial
Mysticial

Reputation: 471529

The error I see is here:

char* uppercasedStr = malloc(sizeof str);

You can't use sizeof() to get the length of a string. You need to use strlen():

char* uppercasedStr = malloc(strlen(str) + 1);  //  Need +1 for terminating null

Here's the other occurrence of the same mistake:

char* copiedStr = malloc(sizeof uppercaseStr);

should be:

char* copiedStr = malloc(strlen(uppercaseStr) + 1);

sizeof(str) only gives you the size of a char pointer, not the length of the entire c-string.

Also note that I omitted the sizeof(char). This is because sizeof(char) is defined to be 1 in C. Therefore it is not needed.

Upvotes: 6

Related Questions