While writing a function to count in how many individual position the string sub
appears in the string s
i found that the for-loop didn't work when using the empty string as s
.
char* s = "";
char* sub = "up";
for(int i = 0; i <= (strlen(s) - strlen(sub)); i ){
//stuff
}
In this case the loop kept going as if the condition wasn't met.
However if i rewrite the condition this way it works as intended.
int max = strlen(s) - strlen(sub);
for(int i = 0; i <= max; i ){
//stuff
}
So i was wondering what is it that could cause this kind of behaviour.
CodePudding user response:
In the condition of the for loop
for(int i = 0; i <= (strlen(s) - strlen(sub)); i ){
//stuff
}
the both expressions strlen( s )
and strlen( sub )
have the unsigned integer type size_t
. So the expression strlen(s) - strlen(sub)
also can not be negative.
As strlen( sub )
is greater than strlen( s )
then their difference will produce a very big value of the type size_t
.
Try this call of printf
printf( "size_t( -2 ) = %zu\n", size_t( -2 ) );
Its output in some system can be for example the following
size_t( -2 ) = 4294967294
while the value if INT_MAX in the same system is equal to 2147483647
.
Moreover as the value INT_MAX
is less than the obtained value of the above expression then you can get an infinite for loop.
What you need is to rewrite the condition the following way
for ( size_t i = 0; i strlen( sub ) <= strlen(s); i ){
//stuff
}