Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Structs always stack allocated or sometimes heap allocated?

I was of the impression that in C#, struct elements are allocated on the stack and thus disappear when returning from a method in which they were created. But what happens if I place the struct-values in a list and return that? The elements survives. Are struct instances sometimes allocated on the heap?

internal struct Stru {   public int i; }  internal class StruTry {   public List<Stru> Get(int max)   {     var l = new List<Stru>();     for (int i = 0; i < max; i++)       l.Add(new Stru {i=i});      return l;   } } 

code printing 0, 1, 2

[Test] public void T() {   var ll = new StruTry().Get(3);   foreach (var stru in ll)     Console.WriteLine("* "+ stru.i); } 
like image 250
Carlo V. Dango Avatar asked Jan 31 '11 16:01

Carlo V. Dango


People also ask

Is a struct stored on the heap or stack?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.

Are structs stored on heap?

That's exactly what the text is telling you, that structs are stored in heap when they're fields of reference types. Structs are also stored in the heap when they're boxed.

Is struct stored in stack?

Most importantly, a struct unlike a class, is a value type. So, while instances of a class are stored in the heap, instances of a struct are stored in the stack. When an instance of a struct is passed to a method, it is always passed by value.

Are structs allocated on the heap Swift?

Short answer, yes, structs that are declared as stored instance properties are allocated in the heap, because the object storage is already in the heap. In Swift any value type (structs included) is allocated on the memory location where it's declared: local variables end up on the stack.


1 Answers

First, read this post from Eric Lippert on The Stack is an Implementation Detail. Follow it with The Truth about Value Types. As for your specific question

Are struct instances sometimes allocated on the heap?

Yes, they are sometimes allocated on the heap. There are lots of examples of when they could be allocated on the heap. If they are boxed, or if they are fields in a class, or if they are elements of an array, or if they are the value of a variable of value type that has been closed over, etc.

But what happens if I place the struct-values in a list and return that? The elements survives.

You're thinking about this the right way, and this is one of the salient points on where a value type might be allocated. See the second post that I referred to on The Truth About Value Types for more details. But just keep The Stack is an Implementation Detail in mind. The key takeaway is that you really don't need to concern yourself with this stuff. You should be concerned with the semantic difference between value types and reference types.

like image 186
jason Avatar answered Sep 20 '22 05:09

jason