Re: snprintf() from "George" at Aug 26, 97 11:54:46 pm

From: Andrew Helm (ashe@IGLOU.COM)
Date: 08/26/97


>
> Currently my buffer system returns a char * so that functions can use it as
> they have always except for freeing it.
[snip]
> The only problem is that each and every other function in CircleMUD doesn't
> use the struct buf_data but a char *.  So after going about changing things
> to a typedef'd buffer *, I ran into the problem that while sprintf is
> easily changed, functions such as log() that take constants cannot be
> modified as such.  send_to_char() is another problem in that regard.
[snip]

If I understand your problem correctly, this should work. When you
create a buffer malloc() enough room for a header as well as the
asked for size of the buffer. Store the header first, then return
a pointer to the first char after the header. Functions that don't
know any better will use it as a normal buffer. Functions that
are supposed to take advantage of the header can access it by
subtracting the sizeof the header from the buffer's pointer.
For example:

(WARNING: Mailer code follows)

struct buf_header {
  size_t size;
  long favorite_color;
};

char *gimme_buffer(size_t n) {
  struct buf_header bufh;
  void *bufptr;

  bufptr = malloc(n + sizeof(struct buf_header));
  bufh.size = n;
  bufh.favorite_color = MAUVE;
  *(struct buf_header *)bufptr = bufh;

  return ((char *)bufptr + sizeof(struct buf_header));  }

int main() {
  char *buf;

  buf = gimme_buffer(256);
  sprintf(buf, "Testing....\n");
  printf(buf);
  sprintf(buf, "This buffer is %ld bytes.\n",
      (*(struct buf_header *)(buf - sizeof(struct buf_header))).size);
  printf(buf);
  exit(0);
}


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | http://democracy.queensu.ca/~fletcher/Circle/list-faq.html |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/08/00 PST