How to assign a value to a string outside the declaration in C ? Bus error/segfault -


i'm trying recode equivalent of strstr() function, after few try got right, here code:

(i know there simpler way did, time wanted try using 3rd string stock occurrence)

 char *my_strstr(char *s1, char *s2)  {    int i, j;    char *tmp;    = (j = 0);    if (s1 != '\0' && s2 != '\0')      {        while (s1[i] != '\0' && s2[j] != '\0')          {            if (s1[i] == s2[j])              {                tmp[j] = s1[i];                j++;              }            i++;          }          printf("tmp = %s\n", tmp);      }    return (tmp);  }    int main()  {    char a[] = "test point123";    char b[] = "point123";    char *ret;     ret = my_strstr(a, b);    printf("ret = %s\n",ret);     return (0);  } 

i output wanted:

tmp = point123 ret = point123 

but sure tried longer string, , that's problems started. here string tried,

char a[] = "test point123456789"; char b[] = "point123456789"; 

and output got it:

tmp = point123456?"1 ret = point123456?"1 abort trap: 6 

with longer string segfault, bus error 10. on other post figured bus error 10 replace segfault on mac os (on i'm coding 1st time, i'm used code on linux), didnt find trap tho.

anyway figured more code problem compiler , i'd know why code function on smaller string not bigger ones, , read how affected value strings i'm using dont understand i'm making error.

so if give me clue on i'm doing wrong i'd appreciate :)

edit

i followed advices in comments, here function after fixed it, runs fine thx.

(again, know dont need tmp , there many other simpler , faster way - meant training (which apparently needed ^^))

char *my_strstr(char *s1, char *s2) {   int i, j;   char *tmp;   = (j = 0);   tmp = malloc(sizeof(strlen(s2)));   if (s1 != '\0' && s2 != '\0')     {       while (s1[i] != '\0' && s2[j] != '\0')         {           if (s1[i] == s2[j])             {               tmp[j] = s1[i];               j++;             }           else             j = 0;           i++;         }     }   return (tmp); } 

in code, tmp automatic local variable function my_strstr(). not initialized explicitly, contains indeterministic value.

later in code, you're directly writing

 tmp[j] = s1[i]; 

using (dereferencing) tmp uninitialized means you're trying access invalid memory location (remember "indeterministic value"?), may not accessible application. invokes undefined behaviour.

solution: need allocate memory tmp before access (dereference) it.


edit:

however, per below comment mr. vlad, logic my_strstr() buggy. once you're incrementing j (index search string) , finding mismatch in between, you're not re-setting 0. maybe want have @ , correct same.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -