Benad's Web Site

Today, as I was trying to port some MFC-specific macros.aspx), I found a curious function: alloca.aspx). In context, it made sense: The macro is supposed to convert some UTF-16 string to UTF-8 ("multibyte"), which requires it to allocate memory, yet it is implemented as a simple macro. What better place to allocate this new temporary than the local stack?

While alloca is clearly non-standard C, it is available on Windows, Linux and Mac. It is quite useful, allowing you to create memory "objects" that will be destroyed when the function exits. But as a design pattern, it may be preferable to move to C++ or even Boehm's garbage collector for C. Its most blatant danger is that it has no error handling whatsoever if the memory block you try to allocate is too big for the stack. So for small strings converted through a macro, it may be acceptable (in a completely non-portable way), but otherwise I'd avoid using it.

Published on September 12, 2012 at 21:32 EDT

Older post: Time-Shifting the Web

Newer post: Java with no SDK