I'm experimenting with one of the functions in the K&R C Programming Language book and using pointers to write the strindex function rather than array notation. I have a strange problem that if I include a printf() statement at either of the two points in my code below then the function returns the correct index (6 in this case), but if I leave the printf() statements out then the function returns -1.
I really can't see why this should make any difference at all and would be grateful for any clarification. Here's my code:
#include <stdio.h>
int strindex(char *a, char *b) {
char *pa;
char *astart = a;
char *pb = b;
int len;
while(*pb++ != '\0')
len++;
while(*a != '\0') {
pa = a;
pb = b;
for(;*pb != '\0' && *pa == *pb; pa++, pb++)
;
if(len > 0 && *pb == '\0') {
return a - astart;
}
//printf("%c\n", *a);
a++;
}
//printf("%c\n", *a);
return -1;
}
int main() {
char *a = "experiment";
char *b = "me";
printf("index is %d\n", strindex(a, b));
return 0;
}
Many thanks
Joe
The problem is the automatic variable len
. Since you don't initialize it, it starts with a indeterminate (garbage) value. Then you increment it, so it will end up as 'garbage + length of b'. Any single change to the compiled code, like an extra printf
call can change the starting value of len
and thus change the behaviour of your program.
The solution: int len = 0;
, and see if you can get more warnings from your compiler. If you are using gcc
, use the -O -Wall -Wextra
flags. Then you should get a warning like:
strindex.c:8: warning: ‘len’ may be used uninitialized in this function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With