Debugging Thread1: EXC_BAD_ACCESS in C

I believe there is are some typo in the program, I fix it below:

void processString(char *str, int *totVowels, int *totDigits)
{
    int i = 0;
    for (i =0; str[i] != '\0'; ++i){
        if(str[i]=='a' || str[i]=='e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' || str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U')
            ++totVowels;
    }
    for (i =0; str[i] != '\0'; ++i){
        if (str[i] == '1' || str[i] == '2' || str[i] == '3' || str[i] == '4' || str[i]== '5' || str[i] == '6' || str[i] == '7' || str[i] == '8' || str[i] == '9' || str[i] == '0')
            ++totDigits;
    }
}

In C, double-quoted things are strings. If you want to compare characters, you need to use single quotes such as 'e' or '\0'

"\0" is a string of 2 NUL characters. This string is stored somewhere in memory, therefore “\0” point to a non-null address.

Another issue is related to pointers:

  ++totVowels;

This will move the local address of the pointer to the next adjacent address. This will not change the value of the counter. To update the value from a pointer, you need to derefence the pointer with the *pointer operator:

*totVowels = *totVowels  + 1;

EDIT due to the informative comment of David C. Rankin

You also need to initialize the counters in the main program. In C, the local variables are not initialized, so their values are undefined.

int main()
{
     char str[50], *p;
     int totVowels = 0, totDigits = 0; // Here, need to initialize the counters
     printf("Enter the string: \n");
     fgets(str, 80, stdin);
     if (p=strchr(str,'\n')) *p = '\0';
     processString(str, &totVowels, &totDigits); //Thread 1: EXC_BAD_ACCESS (code=1, address=0x7ffeefc00000) is shown// 
     printf("Total vowels = %d\n", totVowels);
     printf("Total digits = %d\n", totDigits);
     return 0;
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top