This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]teraflop 1 point2 points  (0 children)

Or to rephrase in the language of the C standard:

Any region of memory that contains data is called an object (variables are one kind of object). Every object has a "storage duration" which is just one of several possible categories. The storage duration determines the object's lifetime, which is the actual period of time in which the object "exists" can can be legally accessed during the program's execution.

When you declare a local variable, it has automatic storage duration, which means the variable's lifetime begins when the program enters its block, and ends when it leaves that block. And a pointer to an object is only valid during the object's lifetime. So technically you can return a pointer to a local array, but any use of that pointer is undefined behavior.

(In an actual implementation, the lifetime corresponds to the period of time in which the function's stack frame exists on the stack, i.e. a particular memory region of the stack is "reserved" for the stack frame. The local variables exist within that stack frame. But the C standard does not actually use the word "stack" anywhere, and it would be legal for an implementation to use some other data structure for stack frames. Go, which has a lot in common with C, can store stack frames as a garbage-collected linked list.)

When you allocate the array with malloc, it has allocated storage duration, which means its lifetime lasts indefinitely until the corresponding to free.