Send_to_char and functions like it are called frequently
throughout the life of the program, and if it is not static, then
memory will keep being allocated and freed from the stack.

True, memory will be allocated/freed on the stack.
This is not a bad thing though.

It costs practically nothing to allocate a variable on the stack.
It is only one integer subtraction operation. (x = x - 100)
Freeing is the same.  It's only one integer addition operation.

Also, it costs exactly the same for a function to allocate one integer on the stack as it does 1000 integers and 1000 string buffers.
It's just one subtraction, no matter how many variables.


There are only 2 reasons to use "static" instead of allocating a variable on the stack.

1.  You want the memory to stick around after your function exits.

        char * myfunc ()
        {
                static char buf[1000];
                strcpy ( buf, "some data" );
                return buf;
        }

        This would not be valid if buf was allocated on the stack,
        since that memory no longer belongs to buf when the function exits.

2.  You're afraid of overflowing the stack.
        The stack has a fixed size.  If you use it up, bad things happen.

        This won't affect you unless you are allocating very large
        things on the stack, or calling very deeply nested functions.

        This will not work, unless your stack is HUGE:

        void myfunc ()
        {
                char buf[100000000];
        }

        The stack will overflow & your program will probably crash.
        However, this will work:

        void myfunc ()
        {
                static char buf[100000000];
        }


On Thu, 7 Apr 2005, Davion Kalhen wrote:

On Apr 7, 2005 6:24 AM, Valnir <[EMAIL PROTECTED]> wrote:
Would it work just as well to do like the following?

if ( !str_cmp(word,"Clan") )
{
    char name[MIL] = fread_string(fp);
    ch->clan = clan_lookup(name);
    fMatch = TRUE;
    break;
}


That will not work. fread_string returns the pointer to a allocated
chunk of characters. If you'll notice, it returns
str_dup(whatisread);, so its allocated there. If you really want to
avoid such things, write a function similar to fread_string but
doesn't allocate memory.

As for my prior rant, const is not needed. I mean, of course, you can
use it. I use static myself. It sets a defined place in the heap for
the variable, meaning it will never need to free/allocate the
variable. Send_to_char and functions like it are called frequently
throughout the life of the program, and if it is not static, then
memory will keep being allocated and freed from the stack. It isn't a
huge deal, I just did it to optimize my send_to_char. Its a
nit-picking thing :P

Reply via email to