32

I am wondering why static arrays don't need to be freed? I know that when creating a dynamic array e.g.

int *p;
p = malloc(10*sizeof(int));

we have to free the allocated memory by using:

free(p);

And for a static array in a function, the static array will be automatically freed when the called function is done.

What I do not understand is: when returning a static array using a function like this:

int *subFunc(){
    static int a[5] = {1,2,3,4,5};
    return a;
}

int main(){
    int *p;
    p = subFunc();
}

If the static array is automatically freed after completing the execution, then how can we still access the values of the static array correctly?

Mat
  • 202,337
  • 40
  • 393
  • 406
BL_
  • 821
  • 1
  • 17
  • 23

5 Answers5

45

If the static array is automatically freed after completing the execution, then how can we still access the values of the static array correctly?

Nope, it's not like that. static variables are initialized before starting main() and its lifetime is the entire execution of the program. So, they can be returned from functions (in which they are defined) and still can be accessed. They are not local (to the functions) which goes out of lifetime when the function finishes execution.

Related, quoting from C11, chapter §6.2.4

An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

Regarding the scope of a static variable inside a function, yes, it is limited to the function itself, as mentioned in chapter §6.2.1,

[...] If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block. [...]

That means, obviously, you cannot use array a outside subFunc(), as a is not visible outside subFunc().

However, when you return the array (returning an array causes a decay to the pointer to the first element of the array, FWIW), as the lifetime of the static array is the entire execution of the program, accessing the returned pointer (surely, within bounds) is perfectly valid and legal.

Chin
  • 19,717
  • 37
  • 107
  • 164
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 5
    `static` locals behave a bit differently from `static` globals : they are initialized not when the program starts, but [when execution first passes their initialization point](http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function). – Quentin May 10 '16 at 13:56
  • 4
    @Quentin Are you sure that is the case for C, too? Can you link some reference? – Sourav Ghosh May 10 '16 at 14:13
  • 2
    Apparently I mixed up C and C++ rules indeed. My bad ! – Quentin May 10 '16 at 15:02
  • 2
    @Quentin @Sourav Doesn't matter too much though, you can't access the funtion-local `static` until you reach its initialization point anyway. And in C, `static` initializers may not have side effects anyway, so you can't really observe when it's initialized. – Tavian Barnes May 10 '16 at 20:25
  • You cannot use `a` outside `subFunc()` but I don't see any reason you can't use a pointer to `a` and use that outside of `subFunc()`. – Z boson May 12 '16 at 08:36
  • @Zboson I don't get the point of your comment. Isn't that exactly what we're discussing here? – Sourav Ghosh May 12 '16 at 08:53
  • @SouravGhosh: Surprising that this basic level C question got so many upvotes, still good question for newbies. – Destructor May 12 '16 at 13:02
21

Static variables continue to exist even after the block in which they are defined terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function. The scope of static automatic variables is identical to that of automatic variables, i.e. it is local to the block in which it is defined; however, the storage allocated becomes permanent for the duration of the program. Static variables may be initialized in their declarations; however, the initializers must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable. - source

Static array or variables will not be freed, when control comes out of that function.

Scope of static variable is local to the function in which it is declared, but its lifetime is throughout the program.

niyasc
  • 4,440
  • 1
  • 23
  • 50
  • 1
    Just today I heard somebody say "no matter if it's inside a function, *a static variable is forever*". – Agostino May 10 '16 at 10:19
  • 2
    @Agostino Of course, since not all static variables are destructed at once, clearly some of them enjoy have a larger values of _forever_ than others. :-) – Frerich Raabe May 10 '16 at 14:56
11

And for a static array in a sub function, the static array will be automatically freed when the called sub function is done.

That is not true. Static arrays are not created when you enter the function, and they are not destroyed when you leave it.

A static variable, and the data inside it, is really a lot like a global variable! The only thing that's local to the function is the name. (You'll hear people talk about the "scope" of the variable -- this means "where can I use the name to refer to it.")

So when you are thinking about the life of a static array, you can mentally replace:

int *subFunc(){
    static int a[5] = {1,2,3,4,5};
    return a;
}

with

int ONLY_USE_ME_INSIDE_SUBFUNC__a[5] = {1,2,3,4,5};  /* global variable */

int *subFunc(){
    int * a = ONLY_USE_ME_INSIDE_SUBFUNC__a;  /* a is the same as the global */
    return a;
}

and then pretend nobody else in your program can touch that global variable.

librik
  • 3,738
  • 1
  • 19
  • 20
  • Incidentally, some compilers will treat the former as the latter, but using an auto-generated name like `$STATIC$fd91a2e7$subFunc_a` which can be guaranteed not to conflict with anything that would be valid in a C file [since user identifiers can't contain dollar signs]. – supercat Jan 20 '17 at 22:50
3

I am wondering why static arrays need not to be freed?

  1. Whatever is not being allocated by a memory management function (malloc, calloc), such as int a[5] need not explicitly be taken care for freeing.

  2. Static variables, such as static int a[5] serve to be accessible within local scope (they retain their values between subsequent calls of the local function). They are created at compile time exactly for this purpose, they have a program lifetime, so it would not be a logical consideration freeing them, even if it was possible, which is not.

  3. Everything else is being masterfully explained in other answers.

user3078414
  • 1,942
  • 2
  • 16
  • 24
2

Static variables inside a function, usually used to maintain some data in a scope of the function over multiple calls for it. They are initialized before main() and their lifetime is as entire execution of the program. So, that wouldn't make sense if they were freed after exiting the function. If you free them, you will crash the very next time you call the function because the they will not be referenced.

Sanich
  • 1,739
  • 6
  • 25
  • 43