Kalinovcic Kalinovcic - 1 year ago 82
C Question

Returning variable-width data by value in C

I'm looking for a way to write a function in C that returns a string of bytes by value. I know that this is usually solved by allocating from the heap, or by making the caller pass a pointer to some buffer. However, in my case, the function must not do any heap allocations for performance reasons (so no malloc, just alloca), and the string length is determined by the function, so there's no way for the caller to know how much space to allocate for it, and there is no defined maximum length either. I also can't split the function into two halves; one that determines the length and one that generates the string.

In short, the callee must be the one that determines the length, allocates the string on stack and fills it. When the function returns, the caller may need to do some fancy stuff in order to store the string safely, but again, it must be stored on the stack, and without calling the function multiple times.

I know this isn't good practice, this would only be used in computer-generated C code. I don't suppose this can be done in "safe" standard C, since everything allocated on the stack is scoped and dies on scope exit. But in reality, those values are still somewhere on the stack (at least until they are overridden), even though the C standard says that reading them is undefined behavior. Does anybody know some good way to do this on x86/x86_64?

Answer Source

This is not solvable in C. Once the function exits, all stack-allocated variables are obliterated. You might be tempted to return a pointer to alloca()-provided address from your function, but that would squarely put you into undefined behavior, and you will be a fair game for optimizer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download