compiles fine, but crashes after printing first value

The program crashes on execution after printing the first value, meant to be printing position of all occurences of an option(struct.option) in string and also printing the option. unique_searchterms is an array of pointers to structs of type options_t and the last pointer in the array points to a struct in which end[0] == '@' to mark the end of the array. Cant see where i'm wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

typedef struct {
     int position;   //irrelevant for this question
     char option[Kmax];  //strings of length 4
     char end[2];     //only added to know where the end of an array of pointers to this struct is
} options_t


//snippet from void function
char *string = "blah blah blah";
i = 0;
int pos;

while((unique_searchterms[i].end[0]) != '@'){
      char *term2match = unique_searchterms[i].option; 
      /* finding all occurences of substrings in string using strstr */
      while((string = (strstr(string,term2match))) != NULL){
	char* ptr = strstr(string,term2match);
	string++;
	pos = ptr - string;
	printf("%d \"%s\"\n",pos,term2match);
      }
      i++;	
}
Last edited on
I do not see any sense in the code snip

1
2
3
4
5
6
      while((string = (strstr(string,term2match))) != NULL){
	char* ptr = strstr(string,term2match);
	string++;
	pos = ptr - string;
	printf("%d \"%s\"\n",pos,term2match);
      }


Let assume that you found term2match in string. In this case string will point to the occurence of term2match. So the next call to strstr

char* ptr = strstr(string,term2match);

will give the same address as string. In this case pos = ptr - string will be always equal to -1. So what is the sense of this code or am I mistaken?
oh i guess my logic went out the window there, haha yes you are right, i'm ok with printing -1 over and over again, the problem is that my function keeps crashing as soon as it is done with the while loop with term2match == unique_searchterms[0].option
how do i debug that, do you see anything there that would do that?
The problem is that after exiting the internal while loop string becames equal to zero. So for the next iteration of the external loop with i equal to 1 your program will be crashed.
Topic archived. No new replies allowed.