Mailing List Archive



Back to the month index Back to the list index

Aaron Abelard (aarona@iquest.net)
Wed, 2 Apr 1997 09:04:13 -0500 (EST)


Date: Wed, 2 Apr 1997 09:04:13 -0500 (EST)
From: Aaron Abelard <aarona@iquest.net>
Subject: Re: [mSQL] escaping characters in c
Message-Id: <Pine.GSO.3.95q.970402085621.12628C-100000@iquest9>

On Tue, 1 Apr 1997, David Sklar wrote:

> hi. does anyone have any handy routines for escaping out ' and \ in
> strings in C? It's (duh) real easy in perl, but I'm writing some stuff
> with the C api now and need to make some strings of arbitrary user input
> safe to insert..

Dave: This is a quick & dirty routine I wrote for a q&d app. Meaning: be
wary of it in production. Just by looking at it I figure it to be a
memory leak. Also, if the search and replace adds more than 50 characters
to the line you'll be doing stuff in memory which isn't yours anymore.
By adding I mean having 50 occurances of a single character search string
which is replaced by a double character search string, 25 of 1 replaced by
3, etc.

That said, it works.

// warning: this routine does modify *line -- adds null's throughout.
// warning: maximum 50 additional characters
char * search_replace(char *line, char *search, char *replace) {

   char * newline;
   char * hit;
   int x=0;
   int y;

   // watch out that you don't add more then 50 characters to new string..
   // this should be dynamically reallocated, its also a memory hog
   newline = (char *) malloc(sizeof(char) * (strlen(line)+50));

   while(x != -1) {
      hit = strstr(line, search);
      if(hit != NULL) {
         hit[0] = '\0'; // temp end string at first hit
         strcat(newline, line);
         strcat(newline, replace);
         line = hit + strlen(search);
      } else {
         strcat(newline, line);
         x = -1;
      }
   }

   return(newline);

}

--
             Aaron Abelard  /  aarona@iquest.net
           IQuest Internet  /  www.iquest.net
          Indianapolis, IN  /  317.259.5050.301  

-------------------------------------------------------------------------- To remove yourself from the Mini SQL mailing list send a message containing "unsubscribe" to "unsubscribe" to msql-list-request@bunyip.com. Send a message containing "info msql-list" to majordomo@bunyip.com for info on monthly archives of the list. For more help, mail owner-msql-list@bunyip.com NOT the msql-list!