tags:

views:

112

answers:

1

Hi there,

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

+8  A: 

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

schot
Ha. Brilliant. Thanks very much Schot. It's working now and I understand the explanation. Given that len was garbage I'm suprised it worked at all.
Joe
Thanks for the edit. I was using -Wall only. Using -O gives the 'may be used uninitialized' warning. Thanks for the tip.
Joe
@Joe: Yes, it is counterintuitive you need to enable optimisation to get certain warnings. Other useful flags are `-ansi` or `-std=c99` in combination with `-pedantic`.
schot