This is my call:
testFunc(0,0,"+++++A+++b+c++++d+e++++f+g+++++h+i","Abcdefghi");
To the function:
void testFunc(int isRight, int step, const char* str1, const char* str2)
{
static int testNum = 1;
printf("test%d: %d\n", testNum++, extendedSubStr(isRight, step, str1, str2));
}
That calls:
int extendedSubStr(int isRight, int gap, const char* str1, const char* str2)
{
// find location of the first char
char * pch;
char * firstOcur;
pch=strchr(str1,str2[0]);
firstOcur = pch;
int i=0;
while (pch!=NULL)
{
i++;
// find next char from the remaining string
pch=strchr(pch+1,str2[i]);
}
if(i==strlen(str2))
{
// return position of the first char
return firstOcur-str1;
}
}
My problem starts when i try to iterate through str1 using strchr() which expects a null terminated string. It keeps looping for some reason. I would prefer not to use memchr().
Why str1 and str2 aren’t nulled terminated? How can i terminate them?
The two strings are definitely null terminated. What happens is that your code iterates past the null terminators.
You need to stop iterating when
str2[i]reaches\0:From the
strchrmanpage:Basically, what happens is that once you reach the null character in
str2, you match the null character instr1. After this, your loop proceed to look for characters that appear past the end ofstr2in memory that followsstr1. Chaos ensues.