Re: xmalloc string functions
- From: santosh <santosh.k83@xxxxxxxxx>
- Date: Sun, 27 Jan 2008 20:54:43 +0530
Malcolm McLean wrote:
Here are six functions implemented on top of xmalloc(). No C
programmer should have any triouble providing the implemetations,
though replace and getquote are non-trivial.
char *dup(const char *str);
char *cat(const char *str1, const char *str2);
char *catandkill(char *str1, const char *str2);
char *tok(const char *str, const char *delims, char **end);
char *midstr(const char *str, int idx, int len);
char *replace(const char *str, const char *pattern, const char *rep);
char *getquote(const char *str, char quote, char escape, char **end);
char *getline(FILE *fp);
All return strings allocated with xmalloc().
dup() is strdup(), and duplicates a string. cat() concatenates two
strings. catandkill concatenagtes two strings, and frees the first. It
also returns dup(str2) is the first pointer is null. It is designed
for building strings in conveneint loops.
tok() is strtok() that takes a string argument instead of using a
global. midstr() takes out a central portion of the string. replace()
is a find and replace, getquote() retrives the next quoted string,
allowing for the quotes themselves to be escaped. You will have to
escape non-quote escaped characters manually, of course. getline()
will be a familiar friend.
I've think we've got something quite powerful here, purely because
none of these functions can ever return null for out of memory
conditions. It massively simplifies string handling.
The library is not terribly efficient and doesn't pretend to be. If
you are doing heavy string processing you might want to look at Paul
Hsieh's better string library, that stores a length parameter with
strings. It is meant to be a few simple functions for easy
manipulation.
Just one suggestion. Usually it's not typical for a /library/ function
to take the liberty of terminating your program. I suggest that
xmalloc() calls a user supplied call-back function if malloc() fails.
The address of the call back need not be passed with every function in
the library. Instead the user could call a call-back register function
before using the other library routines.
The call-back allows the library client to decide the strategy to adopt
on malloc() failure. The client might decide to just call exit() or it
might print a few messages before doing so, or it might decide to
continue with some other part of the program, or whatever...
.
- Follow-Ups:
- Re: xmalloc string functions
- From: Malcolm McLean
- Re: xmalloc string functions
- References:
- xmalloc string functions
- From: Malcolm McLean
- xmalloc string functions
- Prev by Date: Re: When to check the return value of malloc
- Next by Date: Re: xmalloc string functions
- Previous by thread: xmalloc string functions
- Next by thread: Re: xmalloc string functions
- Index(es):
Relevant Pages
|