Reputation: 2125
I cannot find answer to this question. What is the size of data pushed on stack?
Let's say that you push some data on the stack. For example an int. Then value of stack pointer decreases by 4 bytes.
Until today I thought that the biggest data that can be pushed on stack cannot be larger than pointer size. But I did a little experiment. I wrote a simple app in C#:
int i = 0; //0x68 <-- address of variable
int j = 1; //0x64
ulong k = 2; //0x5C
int l = 3; //0x58
Due to my predictions, ulong should be allocated on heap, because it needs 8 bytes, while I am working on 32 bit system (so pointer size is 4 bytes). And that would be very odd, because this is simple local variable.
But it was pushed on stack.
So I think that there is something wrong with the way I think of stack. Because how would stack pointer "know" if he must be changed 4 bytes (if we push int) or 8 bytes (if we push long or double) or just 1 byte?
Or maybe values of local variables are on heap but addresses of those variables are on stack. But this would make no sense, because that's how objects are processed. When I create object (using new keyword) object is allocated on heap and address to this object is pushed on stack, right?
So could someone tell me (or give a link to article) how it really works?
Upvotes: 0
Views: 314
Reputation: 4307
The compiler or run-time environment knows the kind of data you are working with, and knows how to structure into units that will fit onto the stack. So, for example, on an architecture where the stack pointer only moves in 32-bit chunks, the compiler or run-time will know how to format a data element that is longer that 32-bits as multiple 32-bit chunks to push them. It will know, similarly, how to pop them off the stack and reconstruct a variable of the appropriate type.
The problem here is not really different for the stack than it is for any other kind of memory. The CPU architecture will be optimised to work with a small number of data elements of a particular size, but programming languages typically provide a much wider range of data types. The compiler or the run-time environment has to handle the packing and unpacking of data this situation requires.
Upvotes: 1