TIP: Click on subject to list as thread! ANSI
echo: aust_c_here
to: Frank Adam
from: David Nugent
date: 1996-06-10 14:02:16
subject: Find a word

> FA> char *txt;char *pat;char *ptr;
 > FA> txt = (char*) malloc(strlen(buf)+1);
 > FA> pat = (char*) malloc(strlen(wrd)+1);

Just out of interest, why cast the return from malloc()? If it is because
it has no prototype, then you should do the /correct/ thing and include
stdlib.h.

 > char* In_Str(char *buf,char *wrd)  /* case insensitive strstr() */
 > {
 >  char *txt;char *pat;char *ptr,*ptr1;
 >  txt = (char*) malloc(strlen(buf)+1);
 >  if(!txt) return NULL;
 >  pat = (char*) malloc(strlen(wrd)+1);
 >  if(!pat) {free(txt); return NULL;}
 >  ptr = buf;ptr1 = txt; while(*ptr++) *ptr1++ = tolower(*ptr);
 >  ptr = wrd;ptr1 = pat; while(*ptr++) *ptr1++ = tolower(*ptr);
 >  ptr = strstr(txt,pat);
 >  if(ptr) ptr = buf+(ptr-txt);
 >  free(txt);free(pat);
 >  return ptr;
 > }

Excuse my bent towards better readability :-), but here's my version:

  char * In_Str(char const * buf, char const * wrd)
  {
    char *txt, *ptr =NULL;

    if ((txt=strdup(buf)) != NULL)
    {
      char * pat;

      if ((pat=strdup(wrd)) != NULL)
      {
        ptr = strstr(strlwr(txt),strlwr(pat));
        free(pat);
      }

      free(txt);
    }
    return ptr;
  }

Note the 'const' in the parameters. It is a good idea to define the
interface to a function as clearly as possible, which is why const exists.
It also allows you to use the type 'char const *' which you would otherwise
have to cast (for no reason).

If the compiler implements it and stack space isn't going to be a problem,
you could use alloca() for the temporary strings. alloca() is usually
significantly faster than the standard heap allocation functions, and
freeing is automatic.

And yes, there are some non-ANSI functions above, but the non-ANSI
functions used are both commonly available or trivial to implement.

--- MaltEd/2 1.0.b6
* Origin: Unique Computing Pty Limited (3:632/348)
SEEN-BY: 50/99 620/243 623/630 632/103 107 348 360 633/371 634/388 396
SEEN-BY: 635/301 502 503 506 544 639/252 711/401 409 410 413 430 808 809 932
SEEN-BY: 711/934 712/515 713/888 714/906 800/1
@PATH: 632/348 635/503 50/99 711/808 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.