printf() statement makes a difference to my return value? - C Programming -


i'm experimenting 1 of functions in k&r c programming language book , using pointers write strindex function rather array notation. have strange problem if include printf() statement @ either of 2 points in code below function returns correct index (6 in case), if leave printf() statements out function returns -1.

i can't see why should make difference @ , grateful clarification. here's 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 - astart;         }         //printf("%c\n", *a);         a++;     }     //printf("%c\n", *a);     return -1; }  int main() {      char *a = "experiment";     char *b = "me";      printf("index %d\n", strindex(a, b));      return 0; } 

many thanks

joe

the problem automatic variable len. since don't initialize it, starts indeterminate (garbage) value. increment it, end 'garbage + length of b'. single change compiled code, printf call can change starting value of len , change behaviour of program.

the solution: int len = 0;, , see if can more warnings compiler. if using gcc, use -o -wall -wextra flags. should warning like:

strindex.c:8: warning: ‘len’ may used uninitialized in function


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -