Why is 4 bytes of RAM allocated for the parameter variable of a function if the type is short (2 bytes)?

enter image description here

At the request of dgzargo

enter image description here

  • two parameters of type short. try to change the type of one of them - dgzargo
  • @dgzargo What does it have to do with it? I entered two parameters, in operational they are both displayed: 02 00 00 00 - the first one, the second one the same. Introduced two then to see the border by memory between the first and second - Alex
  • Leveling? on the pointer size limit? 32x - 4 bytes, 64x - 8 bytes. - vegorov
  • @vegorov: I think that even on x64 alignment will still be on int , i.e. by 4 bytes. - AnT

2 answers 2

First, in such a code, most likely, no memory will be allocated for the parameters at all - the parameters will be placed in the processor registers.

Secondly, even if your implementation decides to place parameters in memory, most likely it will align them either to the boundary of the native word of your platform, or (more likely) to the border of type int .

A special feature of the variant with alignment on the int type boundary is compatibility with the "old" conventions adopted for calling undeclared functions in the C language: arguments of the type short generate parameters of type int . Most likely this is one of the dominant factors in this case. Compatibility with agreements on the transfer of C language parameters is practically worthless, and there is no point in dealing with some unnecessary “parameter packing” for C ++.

For the same reason, even char arguments will be passed as full-length int , and float arguments as double .

PS You should not be interested in how much memory has been allocated for the transfer of your parameters. It does not matter. Inside the function, your parameters will behave like short values, and their initial values ​​will be passed correctly.

  • When I try to implement a function with a variable number of parameters, using a pointer, the pointer (even if of the short type) gets the address of the first argument, and then moves to 2 addresses in memory, and the argument takes 4. This is where the problem arises. Of course, you can transfer everything as an int type or greater, but still - Alexey
  • @ Alexey: So why are you doing this? Access to variable parameters is done through va_arg , and not through "pointer offset". - AnT
  • I haven’t reached it yet, I learn the language in my free time - Alexey

In your case, the parameters are passed through the stack. And since the program is thirty-two bit, then the stack quantum is corresponding. About the transfer of parameters in Visual Studio is written here and here .

On x86, when they are passed.

What is a stack frame and what and how it is located there is written here and here .