简体   繁体   中英

Are va_arg arguments to functions stored in stack or heap memory?

Question as titled. Are variable argument lists stored in stack memory based on their usage, or are they allocated into the heap?

More importantly to where they are stored: Why are they stored in X?

Are va_arg arguments to functions stored in stack or heap memory?

Maybe.

... By the Standard

The standard has nothing to say about the word "stack" except for stack unwinding in the context of exceptions, and <stack> and std::stack in the context of containers.

The standard has nothing to say about the word "heap" except for is_heap , make_heap , push_heap and pop_heap .

It doesn't say anything about how va_arg et al are implemented, either.

More importantly to where they are stored: Why are they stored in X?

Wherever your implementation and/or ABI chose to store them, they have to be stored somewhere , and that's where the implementation and/or ABI chose - possibly for reasons pertinent to your implementation and/or ABI.

The standard says nothing about the implementation, only the behaviour of va_arg and associated "macros". They don't even have to be macros.

Variable arguments my use the stack, or registers, as per the "normal" conventions for the compiler. Though I recall that for some compilers in the past, while registers were used for normal functions, stack was /always/ used for var arg functions. The gcc compiler family all seem to agree that the call signatures for var arg functions are exactly the same as properly specified functions, and even K&R default extern function calls follow the same register allocation patterns. This means that some of your var args may be in registers and some may be on the stack if there are too many.

va_arg creates an interface to those arguments. Again the standards don't say how, just the behaviour. It may be possible to implement va_arg completely as a context variable, like an instance of a struct, or it may be necessary for the compiler to reserve additional storage, either by manipulating the stack position, or by using a heap. In these cases it is necessary to call 'va_end' to release those heap or stack reservations: this is always best practice.

Then, of course, you pass your instance of 'va_arg' to a child v-function. Now, the va_arg type parameter acts like a reference to the 'va_arg' instance, though C doesn't have a concept of references generally - the nearest similar concept in function declarations is an array argument, which is implemented as a pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM