Sir_Mr_Bman
Sir_Mr_Bman

Reputation: 227

Can't figure out how to debug a bad access error ~> C

So, I have this code:

void stringCounter( char cp[], int counter[] ) {

char c;
for ( int i = 0; strlen(cp); i++ ) {
   c = cp[i];
   // Checking to see if the variable c is alphanumeric...
   if ( isalnum(c) ) {
      if ( c >= 'A' && c <= 'Z' ) {
         counter[c - 'A']++;
      } else {
         counter[26]++;
      }
   }
   }
return;
}

And I have a bad access error on line 5 (of my listed code). I really don't know how to fix this error! I have tried making things pointers, tried not making things pointers, but really can't get it. Usually, I can debug my programs fairly well, but I am really having trouble with this one.
Any help is appreciated.

Upvotes: 0

Views: 49

Answers (2)

P0W
P0W

Reputation: 47824

You are simply incrementing i without any boundary checking

   for ( int i = 0; i< strlen(cp); i++ ) {
                     ^^ fix this

Upvotes: 1

us2012
us2012

Reputation: 16263

Your condition should be i < strlen(cp), not just strlen(cp).

Upvotes: 2

Related Questions