cvisual-studiogccalloca

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

  • 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).