Is there a better way to temp alloc a string of unknown length in C in a way that doesn't require cleanup?
I currently use the following, which does use alloca/_alloca or insert the name your compiler likes for this function
// OLD
// #define stackdup(s) \
// memcpy(memset(_alloca(strlen(s) + 1), 0, strlen(s) + 1), s, strlen(s))
#define stackdup(s) strcpy(_alloca(strlen(s) + 1), s) // refined per comments
// stackndup and stackmiddup can't use strcpy because they need memset 0 ...
#define stackndup(s,n) \
memcpy(memset(_alloca(strlen(s) + 1), 0, strlen(s) + 1), \
s, n > strlen(s) ? strlen(s) : n )
#define stackmiddup(s,pos,n) \
memcpy(memset(_alloca(strlen(&s[pos]) + 1), 0, strlen(&s[pos]) + 1), \
&s[pos], n > strlen(&s[pos]) ? strlen(&s[pos])) )
int main ()
{
const char *address = "123 Main Street";
const char *copy_address = stackdup (address); // "123 Main Street"
const char *address_123 = stackndup (address, 8); // "123 Main"
const char *address_123x = stackndup (address, 55); // "123 Main Street"
const char *address_main = stackmiddup (address, 4, 4); // "Main"
...
}
Takes advantage of how memcpy and memset return the dest, formats the buffer one extra byte to provide for null termination.
Can't use it in a loop obviously as it would allocate on the stack again and again.
char address[] = "123 main street";? Why can't you use that?char address_main[5]; snprintf(address_main, sizeof address_main, "%s", address + 5);. All these macros may seem cute but it makes your code look weird to a maintenance programmer. You could wrap that in a macro if you really want.