So for the sake of training I'm trying to recode the equivalent of an strstr function, after a few try I got it right, here the code:
(I know there are simpler way to do it which I did, but this time I wanted to try by using a 3rd string to stock the occurence)
6char *my_strstr(char *s1, char *s2)
7{
8 int i, j;
9 char *tmp;
10 i = (j = 0);
11
12 if (s1 != '\0' && s2 != '\0')
13 {
14 while (s1[i] != '\0' && s2[j] != '\0')
15 {
16 if (s1[i] == s2[j])
17 {
18 tmp[j] = s1[i];
19 j++;
20 }
21 i++;
22 }
23 printf("tmp = %s\n", tmp);
24 }
25 return (tmp);
26}
27
28
29int main()
30{
31 char a[] = "test Point123";
32 char b[] = "Point123";
33 char *ret;
34
35 ret = my_strstr(a, b);
36 printf("ret = %s\n",ret);
37
38 return (0);
39}
I get the output I wanted:
tmp = Point123
ret = Point123
But then just to be sure I tried with a longer string, and thats where the problems started. Here the string I tried,
char a[] = "test Point123456789";
char b[] = "Point123456789";
and the output I got with it:
tmp = Point123456?"1
ret = Point123456?"1
Abort trap: 6
With longer string I get sometimes segfault, sometimes bus Error 10. On some other post I figured that the Bus error 10 sometimes replace a segfault on mac OS (on which I'm coding for the 1st time, I'm used to code on linux), I didnt find anything about the trap tho.
Anyway I figured its more a code problem that my compiler and I'd like to know why my code function on smaller string but not bigger ones, and I read that it could be how I affected value to the strings I'm using but I dont understand where I'm making an error.
So if anyone could give me a clue on what I'm doing wrong I'd greatly appreciate it :)
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire