'strdupa() implementation for Visual C

I am trying to port a C (not C++) program from GCC to Visual Studio.

The GCC specific function strdupa() is widely used in this program. Is there any way to implement this function for Visual C.

PS. I understand that it uses alloca() and it is unsafe. But it works very well on GCC now and I think it is safer to implement the same function in one place then change the logic of program. I also don't want performance to decrease.



Solution 1:[1]

I'd implement it as a macro:

#define strdupa(a) strcpy((char*)alloca(strlen(a) + 1), a)

That way it is not in a function and so the alloca'd string won't be freed prematurely.


Note: From man:

On many systems alloca() cannot be used inside the list of arguments of a function call, because the stack space reserved by alloca() would appear on the stack in the middle of the space for the function arguments.

… i.e. (from "GNU C Library Reference Manual"):

Do not use alloca inside the arguments of a function call—you will get unpredictable results, … . An example of what to avoid is foo(x, alloca(4), y).

Solution 2:[2]

My way to implement it as function. Not sure that it is safe, but it seems it works:

__forceinline char* strdupa(const char* s) {
    return strcpy((char*)_alloca(strlen(s) + 1), s);
}

But I think macro it a better way than using __forceinline

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Sandro