Fog Creek Software
g
Discussion Board




Why Struct in the stack?

Regarding

Wouldnt this be storing a structure in a stack

{
struct s = new Struc()
<some other ops>
}

or do you mean for the life of the process, rather than until the function exits. but practically why would you ever have to do this? couldn't you store it in the heap, and just get references from stack?

{
struct s = publicCollection.getStruct()
}

The Artist Formerly Known as Prince
Wednesday, January 14, 2004

In all languages I am familiar with, the use of new (or, in the case of C, malloc) will place the data on the heap, not the stack.

Regarding your second question, the behavior of your code snipped depends on the language :)

In C, it's not valid (you'd have to call a function like memcpy). In C++ this will call an assignment operator, and do a copy. In java, it will assign as a reference.

The most common use of the heap over the stack is probably (at least in languages where you get a choice, like C. Java places all objects in the heap) when you don't know what or how much you'll need when you compile the program, i.e. when you read the data from a text file to create a data structure.

Feel free to correct me if I've misunderstood the question.

Mike Swieton
Wednesday, January 14, 2004

I'm not sure I follow the original question, but C# uses the syntax:  V v = new V(...) to construct valuetypes that are placed on the stack.

Very confusing syntax to anyone who has programmed in C(++).

Rob Walker
Wednesday, January 14, 2004

And if it is .Net - like syntax new-ing up struct (value type) will actually allocate it on the stack.
Note: it really hard to tell what language you are refering to as there are multiple "curly braces" based ones

WildTiger
Wednesday, January 14, 2004

In .Net / C#, Value Types (defined as struct) like int, long, etc go on the stack, while Reference Types (defined as class) go on the heap.

I suspect this is for performance reasons, as items on the stack are much quicker to access.

Also, the compiler knows exactly how much space to allocate on the stack for struct-based items, although it has to "cheat" with strings and object references, where it'll stored pointers to the actual string/object instances.

Steve Jones (UK)
Thursday, January 15, 2004

Creating an automatic structure in C will create it on the current stack.

struct fred
    {
    int member_1;
    int member_2;
    char member_3;
    }our_fred;

That is, declaring it within the body of the function, the defining could be elsewhere.

Simon Lucy
Thursday, January 15, 2004

*  Recent Topics

*  Fog Creek Home