Acronyms - Segmentation Fault during test runs

I am getting Segmentation Fault during my test runs. My code works fine on my local machine with sample string. Below is the function code.

static char to_upper(char letter){
    if(letter >= 'a' && letter <= 'z')
    {
        return letter - 32;
    }
    return letter;
}

char *abbreviate(const char *phrase){
    int size = strlen(phrase);
    if(size == 0){
        return NULL;
    }
    int size1 = 1;
    char* abrev = (char*)malloc(sizeof(char) * (size1 + 1));
    // abrev[0] = to_upper(phrase[0]);
    char letter1[] = "A";
    int space = 0;
    
    for(int i = 0; i < size; i++){
        if(i == 0){
            if((phrase[i] >= 'a' && phrase[i] <= 'z') || 
               (phrase[i] >= 'A' && phrase[i] <= 'Z')){
                
                letter1[0] = to_upper(phrase[i]);
                strcpy(abrev, letter1);
                // abrev[size - 1] = letter1[0];
                size1++;
                abrev = realloc(abrev, size1 + 1);
            }
        }
        if((!(phrase[i] >= 'A' && phrase[i] <= 'Z')) && 
           (!(phrase[i] >= 'a' && phrase[i] <= 'z')) && 
           (phrase[i] != '\'')){
            space++;
           }
        else if(space != 0){
            if((phrase[i] >= 'a' && phrase[i] <= 'z') || 
               (phrase[i] >= 'A' && phrase[i] <= 'Z')){
                letter1[0] = to_upper(phrase[i]);
                strcat(abrev, letter1);
                // abrev[size - 1] = letter1[0];
                size1++;
                abrev = realloc(abrev, size1 + 1);
            }
            space = 0;
            
        }  
        if (abrev == NULL) {
            // Handle realloc failure
            free(abrev);
            return NULL;
        }
        
    }
    abrev[size1] = '\0';
    return abrev;
}

If you run all the tests locally, you should get the same failure locally. You may want to look at the inputs the tests use to call the function. Some inputs may be edge cases.

One issue is that strcat only works if both arguments are null-terminated:

                strcat(abrev, letter1);

However, malloc makes no guarantee about what you will find in your allocated memory:

                 char* abrev = (char*)malloc(sizeof(char) * (size1 + 1));

The strcpy near the top of your loop will put a '\0' at the end of abrev, but that will be skipped if the phrase doesn’t start with a letter.
Try putting

    abrev[0] = '\0';

before the start of the loop.

Thanks for the feedback. I forgot to test the case where the phrase is NULL.

Thanks for the feedback. I also changed malloc to calloc and I added the ‘\0’ character on last index of array just to make sure everythings work.

You shouldn’t be manually testing anything. You should be running the supplied unit tests.