Re: Thnx for memcpy/gdb help :)

From: Tel Janin Aellinsar (icarus@Loomis.Berkshire.NET)
Date: 04/11/96

On Thu, 11 Apr 1996, Rasmus Rxnlev wrote:

> [SNIP]
>   file = fopen(fn,"wt");
>   if (!file)
>   {
>     sprintf(buf, "ERROR: Unable to get filedescriptor in write_alias()");
>     mudlog(buf, NRM, MAX(LVL_JUDGE, GET_INVIS_LEV(ch)), TRUE);
>     return;
>   }
> buf is c pointer to a char, and fn is an array of chars (the filename:)

As in what?  Like this:

char *buf, fn[size];

Or like this:

char buf, *fn = malloc(size);

Well, it doesn't really matter.  sprintf()'s first argument is a pointer, 
which is what I think you said.

> Shouldnt it work flawlessly ? I mean it's not that I don't assign anything
> to buf... Well, I'm actually wondering if it's because buf is a pointer 
> to a char... should it be an array of chars ? (the mud doesnt crash 
> whenever an alias is written though..).


  char var[512];

Is functionally the same as:

  char *var;
  var = (char*) malloc(512);

If you pass the first var (var1) to a function, is becomes the same as 
the second var (var2) as far as the function can see, assuming they're 
assigned the same location in memory.  i.e., if you call func(var1), 
there is no way that func() can tell that var1 is a statically-allocated 
segment of memory rather than dynamically-allocated (malloc()'ed) segment 
of memory.  All you do is give the function the address of the first 
charater of the string.  This is why, for many functions that use data of 
type void* rather than char*, you need to get a length argument too, to 
prevent a buffer overrun (which should give you a segmentation fault).

I don't think I could tell you what your problem is there, but you don't 
need to use sprintf(), which is slow and unwieldy.  Just pass the error 
message directly to mudlog() or, if that bothers you, assign the error 
message to buf or use strcpy() to copy it.  In summary:

1. mudlog("ERROR: Unable to ...
2. buf = "ERROR: Unable to ...
   mudlog(buf, ...
3. strcpy(buf, "ERROR: Unable to ...
   mudlog(buf, ...

All of these are perfectly legal, and it's really hard to get an error on 
all but the last one.  Only use sprintf() if you've got some additional 
information or other to give.  For example,

  sprintf(buf, "ERROR: %s: %s.", fn, sys_errlist[errno]);

would give you a much more lucid error message.

Tel Janin Aellinsar             
McCoy Enterprises Corporation          Shayol Ghul Resort and Health Spa
Berserker Dragon, Knights of the Cosmos             icarus@BERKSHIRE.NET

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