# Thread: Segmentation fault with structs and char pointers

1. > Says:
> 1) start the loop at -1.
> 2) When the loop is done,
> 2a) increment i
> 2b) test with strlen1
Nope

The test is performed before the body of the loop is executed. Think while loop with automatic initialisation and iteration steps thrown in.

Both these do the same thing.
for ( i = -1 ; ++i < 10 ; )
for ( i = 0 ; i < 10 ; i++ )

2. Originally posted by CornedBee
Actually the condition IS evalutated before the first run. But since this code is so uncommon, it should be the other. Simply for the sake of readability.
So right. Don't know what I was thinking.... Must've had a brain cramp.

Sorry for the misinfo.

3. Code:
```bool Equal(char *str1,char *str2) //Is this the problem?
{

if(strlen(str1) != strlen(str2) )
return(false);
for(int i=-1;i<=(int)strlen(str1); ++i)
{
if(str1[i] != str2[i])
{
return(false);
}
}

return(true);
}```
MANY mistakes.

1. The loop is starting at -1, not 0.
2. You are doing MASSIVE amounts of iteration -- this algorithm operates on order N^2
3. What if str2 is shorter than str1? You walk right off the end of the array.
4. Be const correct. Yes, a const char * will implicitly convert to a char *, but this is a deprecated feature and should NOT be used.

Code:
```bool Equal(const char *str1, const char *str2)
{

int i;
for(i=0;str1[i] && str2[i]; ++i)
{
if(str1[i] != str2[i]) return false;
}

if (str1[i] || str2[i]) return false;
return true;
}```
A few points to note:

1) str1[i] && str2[i] -- this keeps the loop going until it hits the end of either string (assuming the return doesn't take place)

2) str1[i] || str2[i] -- This checks to see if it hit the end of only one of the strings, but not the other (otherwise, it would say "cat" and "catalog" were the same)

4. ## Feeling defensive...

Hey! I never said that str1[-1] was beign evaluated! That wasn't me!!! All I said, was that pre or post-incriment only affected the conditional (middle) part of the for-statement.

And, I said that these run-time crashes are often caused by writing beyond an array's boundries.

Keybone,
Your logic was OK, but I still recommend using a more standardized form of the for-statement whenever possible.

5. 3. What if str2 is shorter than str1? You walk right off the end of the array.
If that's the case, the first if statement stops the function and the main loop is never executed.

6. Originally posted by CornedBee
If that's the case, the first if statement stops the function and the main loop is never executed.
Ah, quite right.