doing nasty things with internal static variables

Duane Richard LaMont lamont at uts.amdahl.com
Fri Mar 22 15:44:38 AEST 1991


In article <1991Mar19.183920.18911 at rice.edu> fontenot at comet.rice.edu (Dwayne Jacques Fontenot) writes:
>I have found myself doing this because it works, but I am curious if it
>is a common practice or if it is highly likely to get me into trouble:
>
>char *foo()
>{
>  static char string[64];
>
>  ...
>  return(string);
>}

Thus far, the followups to the posting above have focused on the fact
that this method works and is common practice, etc.  However, I would
like to point out one caveat which I've experienced.

I once wrote a function like foo which returned different strings based
on the value of a lone argument.  One of my less experienced co-workers
attempted to use it and did something like this:

    char *a, *b;

    a = foo(x);
    b = foo(y);
    printf("a = %s; b = %s\n", a, b);

Much to her surprise, string a was always identical to string b
regardless of the values of x and y.  I pointed out that a and
b both pointed to the static buffer within foo which was overwritten
on each call.  So, I was feeling pretty good about myself until the
next week when I wrote something like this:

    bar(foo(x), foo(y));

My new rule of thumb: If the higher level application programmer
is likely to call my function multiple times and save the results
separately, make him pass in his own buffer.  This saves him
from making calls to strcpy.

Also note that, at least on my system, asctime uses a static return
buffer and has this caveat listed on the man page.

Rick LaMont



More information about the Comp.lang.c mailing list