开发者

To find the substring in a given text.. C programm

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 its giving me a run-time error "Segmentation Fault". 开发者_高级运维What is this error all about.. and why is it giving this error..

Thanks..


temp is uninitialized.


You need to allocate memory for temp - currently it's just a dangling pointer. You can use malloc for this but note that the caller will need to ensure that this storage is subsequently freed.

For example:

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;
}


It means that your code has violated some restriction set up by the operating system, in this case you are writing to memory that you do not have the right to write to.

This is because your temp variable is just an uninitialized pointer, it doesn't contain the address of memory where you are allowed to write.

If you expect to write length + 1 characters, it must be pointing to at least that many bytes worth of space.

Since you expect to return the string, you need to either make it static (but that can be dangerous), or allocate the space dynamically:

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


I am making a copy of the sub-string into another pointer, this is the just the simple way of finding one substring of a given string..

Hope i am that very simple way in the correct manner..

Also, The methods given by SysAdmin,, looks pretty complex ones, but still thanx for the suggestion.. I will try and learn those as well.. But if you can tell me whether i have implemented the very basic pattern searching algorithm correctly, then it would be very kind..

Thanks..


while the answer is obvious - i.e temp is not initialized, here is a suggetion.

If your intention is to find a substring in another string, few alternatives are,

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

Update: Initialy I thought this question was related to finding the substring (based on the title). Anyway, this looks like strchr() implementation.


It is obvious from the code that you missed to allocate / initialize the pointer *temp. It is pointing to nowhere.

You either have to use malloc or strdup and do the rest. But yeah , you may also want to explore using strncpy (null terminate) to simplify the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜