Reputation: 3058
The function _alloca (alloca) allocates memory on the stack, which does not require "free".
Is it possible to write a function that allocates on the stack in C?
Another way of phrasing it: _alloca does it!
Or is this not possible in C for other reasons including: 1) The functionality is written in ASM 2) It is a characteristic of the C run-time library.
The reason I am interested in writing an alloca-like function goes like this:
void func (const char *path, const char* filename)
{
char s[1024];
snprintf (s, sizeof(s), "%s/%s", path, filename);
}
But I would prefer:
void func (const char *path, const char* filename)
{
char *s = alloca_sprintf ("%s/%s", path, filename);
// ... No need to free.
}
Thanks in advance to anyone knowledgeable in this subject. asnprintf is an improvement over using a fixed-size buffer, but still requires clean-up.
Upvotes: 0
Views: 160
Reputation: 215357
Doing alloca
as a function is fundamentally impossible, since the semantics of alloca
are for the storage lifetime to end on function return. The alloca
provided by some compilers is not a function but a builtin. If may be possible to achieve what you want with a macro that uses alloca
, but in general, alloca
is a very bad idea. There is no way for alloca
to report failure; it will just silently clobber unrelated data and/or crash if you try to allocate too much.
Upvotes: 0
Reputation: 8923
What you are suggesting is that the memory allocation on the stack take place inside the function alloca_sprintf(), which then returns it. The problem is that the memory allocation would be gone by the time the function alloca_sprintf() returns - because it's stack collapses as soon as it returns. The memory would be invalid.
Upvotes: 0
Reputation: 225012
If your goal is just to minimize the consumed stack space, you don't need anything more than C99 VLAs:
void func (const char *path, const char *filename)
{
char s[strlen(path) + strlen(filename) + 2]; // +2 for '/' and null terminator
sprintf(s, "%s/%s", path, filename);
...
}
This is the same functionality you'd get from alloca
, and it's standard!
Upvotes: 2
Reputation: 108
I believe it should be possible, but it depends on your toolchain (specifically, how the compiler uses the stack) and your processor architecture - basically, the compiler might need to know which variables' relative locations might change (for variables it's placed on the stack, as the top of the stack will change - only for variables on the stack, since a compiler may place some variables entirely in registers).
As such, I'd expect any existing implementations of a function like _alloca() to be tied to the specific version of the compiler (and architecture) that the runtime library belonged to. It may or may not be easy to implement yourself, but it may not be very portable unless you're able to use some trick (with C++ templates maybe?).
Upvotes: 0