Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 18 Feb 2008 17:41:42 -0600
From:      Tim Daneliuk <tundra@tundraware.com>
To:        tundra@tundraware.com
Cc:        Gary Kline <kline@thought.org>, FreeBSD Mailing List <freebsd-questions@freebsd.org>
Subject:   Re: is there an easier way?
Message-ID:  <47BA17B6.20906@tundraware.com>
In-Reply-To: <47BA14F8.4060109@tundraware.com>
References:  <20080218230351.GA28000@thought.org>	<47BA1375.2010108@tundraware.com> <47BA14F8.4060109@tundraware.com>

next in thread | previous in thread | raw e-mail | index | archive | help
Tim Daneliuk wrote:
> Tim Daneliuk wrote:
>> Gary Kline wrote:
>>>     To my fellow C nerds,
>>>
>>>     It's been a  great manny years since I wrote this appended
>>>     snippet.  Now I can't remember why (of if ) I need all the
>>>     strcpy() calls.   Is there a simpler, more logical way of     
>>> printing a bunch of string by snipping off the left-most?
>>>
>>>     In short,, can anyone 'splain why strtok needs all this?
>>>
>>>     tia,
>>>
>>>     gary
>>>
>>>
>>
>> I don't think you need the copies.  This works just as well:
>>
>> #include <stdio.h>
>> #include <string.h>
>>
>> main()
>> {
>>   char *bp, *tok;
>>   char *delim=" ", s1[256]="abc def ghi jkl mno.";
>>
>>   bp = s1;   /* Now both point to the literal string to be tokenized */
>>
>>   while ((tok = strtok(bp, delim)) != NULL)
>>   {
>>     bp = NULL;
>>     printf("tok = [%s]\n", tok);
>>   }
>> }
>>
> 
> 
> Ooops ... wasn't paying attention.  While the printed output is the 
> same, doing
> it this way is destructive to the original s1 string - which may matter 
> (or not)...

So, to protect the original string, you do have to copy the original
string to a new buffer:


#include <stdio.h>
#include <string.h>

main()
{
   char *bp, *tok, buf[256];
   const char *delim=" ", s1[256]="abc def ghi jkl mno.";

   bp = strcpy(buf, s1);

   while ((tok = strtok(bp, delim)) != NULL)
   {
     bp = NULL;
     printf("tok = [%s]\n", tok);
   }
}


So, at least we eliminated the first strcpy in your code:

   char *bp, buf[512], *tok, tstr[512];
   static char *delim=" ", s1[256]="abc def ghi jkl mno.";

   bp = strcpy(buf, tstr);

This accomplishes nothing and may not even be safe - strcpy() copies
until it hits \0.  I do not recall if the declaration of tstr[512]
intializes it to \0.  If not, then the strcpy() is going to keep
running until it finds one, overwriting the end of buf[] and probably
causing core dumps or other evil...
-- 
----------------------------------------------------------------------------
Tim Daneliuk     tundra@tundraware.com
PGP Key:         http://www.tundraware.com/PGP/




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?47BA17B6.20906>