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;
}