Find a substring in the given text .. C-program

char *substring(char *text, int position, int length)
{
   int i, j=0;
   char *temp ;

   for(i=position-1; i<position+length-1; i++)
   {
     temp[j++] = text[i];
   }
   temp[j] = '\0';

   return temp;
}

Hi What is the error in the following code. I am trying to run this on Fedora Machine. And that gives me an error at runtime "Segmentation Error". What is this error? .. and why does it give this error.

Thank..

+3
source share
6 answers

You need to allocate memory for temp- at the moment, this is just dangling pointer. You can use mallocfor this, but note that the caller will need to ensure that this storage is subsequently freed.

For instance:

char *substring(const char *text, int position, int length)
{
   char *temp = malloc(length + 1);
   int i, j;

   for (i = position, j = 0; i < position + length; i++, j++)
   {
       temp[j] = text[i];
   }
   temp[j] = '\0';

   return temp;
}
+3
source

temp uninitialized.

+6
source

, - , , , .

, temp , , .

length + 1, , , , .

, static ( ), :

if((temp = malloc(length + 1)) == NULL)
  return NULL;
+2

- , .

, ,

1. use C strstr(...)
2. Robin-Karp method
3. Knuth-Morris-Pratt method
4. Boyer Moore method

Update: , ( ). , strchr().

0

, .

, .

, , SysAdmin, , thanx .. . , , ..

..

0

, , / * temp. .

malloc, strdup, . , strncpy (null terminate), .

0

Source: https://habr.com/ru/post/1744096/


All Articles