View Single Post
Old 05-15-2002, 09:48 AM   #5
KaVir
Legend
 
KaVir's Avatar
 
Join Date: Apr 2002
Name: Richard
Home MUD: God Wars II
Posts: 2,052
KaVir will become famous soon enoughKaVir will become famous soon enough
As Unifex points out, you're returning a pointer to a stack-based variable, which becomes invalid as soon as you exit the function.  As well as the two suggestions provided (using str_dup() to store the variable on the heap, or the static storage class specifier to allocate space for it in the data segment) there are also a couple of other possibilities which spring to mind.

The first is to add an extra argument to the function, which is a pointer to an allocated chunk of memory (which CAN be on the stack).

The second is to encapsulate the array within a structure and return the entire structure from the function (although this is rather inefficient).

Aside from the memory management issue, you're also not initialising the buf array.  You do assign a value to the first element ("["), but you don't put a NUL ('\0') character after it.  The strcat() requires an initialised string.  You could either assign the second element of buf to NUL, or add the initialisation to the declaration like so:

char buf[256] = { '\0' };

That will set every element of buf to NUL.

I'm also rather confused by Unifex's statement ""char buf[256];" is actually "char *buf"".  Unifex, would you care to elaborate on this?  "char buf[]" and "char *buf" are equivilent as function arguments, but they are certainly not the same.  Am I misreading something in your post?
KaVir is offline   Reply With Quote