简体   繁体   中英

Own C library with memory-related issues

I am writing a C library for strings management, it would be like python interface as much as possible, but I have the following question:

Should my library allocate memory, or the client has to do it?

for example, see my center method:

char * center(char * str, int width, char fillchar)

The issue with this approach is that the client has to free every time this method is called.

See more here:

https://github.com/jiss2891/pystrings

Lots of times when I'm writing such functions, they're for formatting purposes, whereby the centered or otherwise-prettyfied string won't be needed for long. When that's a safe assumption, I typically declare a static wraparound buffer in the function, something like the following...

char *center_or_whatever ( char *instring, int some_param /*,etc*/ ) {
  /* --- wrap-around buffer --- */
  #define NBUFFS 999
  #define BUFFWIDTH 999
  static char buffer[NBUFFS][BUFFWIDTH];
  static int  ibuff = 999999;
  char *outstring = NULL;
  /* --- assign next buffer to outstring --- */
  if ( ++ibuff >= NBUFFS ) ibuff=0;
  outstring = buffer[ibuff];
  /* --- check to make sure instring and other params won't make
     outstring exceed BUFFWIDTH, truncate (or whatever) if necessary, etc --- */
  /* --- now do whatever your function's supposed to do --- */
  strcpy(outstring,instring); /* just for example */
  return ( outstring );
  } /* --- end-of-center_or_whatever() --- */

...So now, nobody has to malloc or free anything, so long as the user won't be needing the output for more than NBUFFS calls to the function, and as long as the output won't ever need to exceed BUFFWIDTH chars. Those arguably aren't safe assumptions, but I frequently find something like NBUFFS=64 and BUFFWIDTH=128 are more than safe enough for the purposes of whatever I'm programming at the time. And the static allocation of [64][128] bytes is pretty much unnoticeable. So, most of the time for me, the ease and safety of not worrying about malloc/free is well worth the extra few bytes and extra few lines of code.

Note that you can also declare one big, long static char buffer[99999]; and maintain a pointer that's initialized static char *buffptr=buffer . Then during each call, assign outstring to the current buffptr , bump buffptr , and wrap it around when it would overflow. That's a little more flexible, and takes a few (but not many) extra lines of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM