Jonathan Sternberg
Jonathan Sternberg

Reputation: 6647

Static Variable Pointer?

Is this illegal/dangerous?

int* static_nonew()
{
    static int n = 5;
    return &n;
}

The compiler doesn't seem to have a problem with it, but is the pointer location itself protected from being overwritten when someone else needs memory?

EDIT: A little bit more of an explanation of why I asked this question. Note: I'm programming in C++, I just tagged it as C because it seemed to be more of a C than C++ question.

I have a class that's supposed to return a static map. I only want this map initialized once throughout the program as there doesn't seem to be a need to do it multiple times. For this reason, I was going to have something like this:

static std::map<std::string, Transition*> transitions;
static Transition trans1(transitions, ...);
static Transition trans2(transitions, ...);
return &transitions;

The Transition classes constructor would add itself to the transitions. In that way, it would create the transitions once and then return a pointer to them. I just remember that if you create a reference to a variable allocated on the stack, it could get overwritten very easily and was "unsafe". I was just a bit confused with exactly how static variables created within a function work.

Upvotes: 8

Views: 6542

Answers (4)

rhinoinrepose
rhinoinrepose

Reputation: 2151

It's legal but remember that you'll only ever have one instance of transitions and that it'll get constructed before you main() because it's declared static. It's pretty much like having a global variable.

Upvotes: 1

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

Assuming you've meant int* static_nonew( )

Once you've returned a pointer to any memory location, then that memory can be overwritten, there are no protection guarantees in C.

Also, if you pass this pointer to free, the behavior is undefined, so sometimes it will be OK, and sometimes it will dump core.

On the other hand this is totally legal code. Also, substitute int to some struct that you need to initialize once, and it's a pretty useful idiom.

Upvotes: 0

Amardeep AC9MF
Amardeep AC9MF

Reputation: 19044

This is just a get function to the pointer of a static variable. There is nothing illegal about it. It is not intrinsically any more dangerous than any other type of static data.

But static data:

  1. creates tight coupling
  2. hampers re-entrancy
  3. creates the opportunity for subtle bugs
  4. is often a sign of weak design
  5. should be used very judiciously

The static storage class modifier means the memory will be reserved for this variable for the life of the process.

Upvotes: 6

Nils Pipenbrinck
Nils Pipenbrinck

Reputation: 86363

This is valid code, and useful.

A lot of singleton-factories are built like this.

Upvotes: 5

Related Questions