Thread: How bad is it to use alloca()?

  1. #31
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Okay, so I googled it and I read around a bit. Also, there was condescension somewhere? Lol wut?

    First, I read the man page on alloca. They do claim that it is both machine- and compiler-dependent and that they discourage its use but do highlight that it can improve the efficiency of certain applications. And that agrees well with the theory. Granted, new() may be near just as fast but I want to avoid it because I want some large number of threads running the same code. Stack allocations vs. heap allocations in this case have the potential to be costly (if using new()) when running on some 16 core processor because now that's 16 searches through the pool instead of just throwing something on top of the stack 16 times.

    It's one more thing that can make code faster and there's a Windows version and the Windows version even got an upgrade to _malloca. _malloca

    There's even a _freea to go with _malloca which I think is awesome.

    But phantom, the man pages also highlight what you said as well. It can't be used as arguments (which freaked me out, I've never once thought of using a function's return as an argument) and it doesn't return a failure so you're free to go beyond the stack. But if your OS can't handle a SIGSEGV signal, then please, stop using a OS from 1984. Sorry, that last line isn't meant to attack anyone, I just think it's a funny joke because I think kernels are strong nowadays (that's like a kernel-level thing, right?). I've crashed tons of code (trust me) and so far it's all been fine. If your code crashes, hopefully your computer won't run havoc and delete your system. What is this, 1995?

    And if not alloca, how am I supposed to get variable length arrays on the stack in C++ if ISO C++ forbids it? I tried googling it and the answer was to use new() which made me run away in fear. C gets it, so why not us?

  2. #32
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by MutantJohn
    how am I supposed to get variable length arrays on the stack in C++ if ISO C++ forbids it?
    Bite the bullet and use a compiler's language extension

    That said, I don't think that it is actually a requirement for a C implementation to have variable length arrays on the stack.

    Quote Originally Posted by MutantJohn
    C gets it, so why not us?
    The variable length array feature was only standardised in C99, but C++98 was based on C89/C90. I guess that it was a rather low priority to introduce a language feature that generally is not needed given that std::array and std::vector exist in C++11.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #33
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by MutantJohn View Post
    But phantom, the man pages also highlight what you said as well. It can't be used as arguments (which freaked me out, I've never once thought of using a function's return as an argument) and it doesn't return a failure so you're free to go beyond the stack. But if your OS can't handle a SIGSEGV signal, then please, stop using a OS from 1984. Sorry, that last line isn't meant to attack anyone, I just think it's a funny joke because I think kernels are strong nowadays (that's like a kernel-level thing, right?). I've crashed tons of code (trust me) and so far it's all been fine. If your code crashes, hopefully your computer won't run havoc and delete your system. What is this, 1995?
    Linux is pre-94, too, you know. And while we're at it, please stop using monolithic operating systems that puts everything inside the kernel. That means every time some bloody thing in the kernel crashes, your operating system dies. And yes, your beloved Linux is a monolithic OS. Windows falls under this category, as well, but it's actually a little better in this aspect (there are user mode drivers, and the graphics is user mode post-vista).

    And if not alloca, how am I supposed to get variable length arrays on the stack in C++ if ISO C++ forbids it? I tried googling it and the answer was to use new() which made me run away in fear. C gets it, so why not us?
    VLAs, as implemented in C99, were pretty bad, as experience apparently has shown (I've read it somewhere; I have no proof; hence "apparently"). That's also why std::dynarray was delayed, due to uncertainties and issues.
    Anyway, to answer your question... use memory pools! Pre-allocate some memory at start, for each thread if you want, then allocate objects from that pool. Completely 100% C++, no need for alloca and fast!
    Of course, you are still free to use your alloca, if you really want.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #34
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Elysia, how dare you insult Linux. How. Dare. You.

    I might wind up not even using alloca but I do like the option of just saying yolo and going for it.

  5. #35
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by MutantJohn View Post
    Elysia, how dare you insult Linux. How. Dare. You.
    How dare you insult Windows.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #36
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I guess I should feel doubly insulted since I have both of them installed
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #37
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Elysia, I'm having a really hard time admiring you right now.

  8. #38
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by MutantJohn View Post
    Elysia, I'm having a really hard time admiring you right now.
    You don't need to admire me.
    You only need to admire beautifully written C++ code, regardless of who wrote it.
    You also need to admire microkernel operating systems. Those are a piece of art, unlike monolithic operating systems...
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #39
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by MutantJohn View Post
    Elysia, I'm having a really hard time admiring you right now.
    I really hope CBoard in general does not have the reputation of being populated by programming demigods.

  10. #40
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    Also, there was condescension somewhere?
    O_o

    If you still perceive my post as condescending, I apologize.

    If that was more "Which bit is supposed to be condescending?", I removed part of my post.

    Stack allocations vs. heap allocations in this case have the potential to be costly (if using new()) when running on some 16 core processor because now that's 16 searches through the pool instead of just throwing something on top of the stack 16 times.
    I get the feeling you learned about the generic forms of "nearest fit list" style allocators without ever studying more modern designs. (Granted, still decades old techniques in any event.) You need not thing of heap allocation as always being a mutually exclusive lock around linear polling for the next block big enough to store the size requested. You have fallen into the classic trap: "If `malloc' isn't fast enough, programmers are doomed to write their own implementation.". (I probably butchered this quote, and I have no idea who said it.) The thing is, modern allocator designs for C++ know the "Best Practices" of C++ a lot better than you.

    Code:
    void DoSomething(/**/)
    {
        some_smart_pointer s = new int[4];
        // do something
    }
    // ...
    int main()
    {
        while(/**/)
        {
            DoSomething(/**/);
        }
    }
    This form of allocation is extremely common in modern C++ thanks to "Best Practices" and canonical idioms--like "type erasure" and "expression templates"--which imparts the need for an allocator that uses some method of stack-like caching internally. Combine those techniques with "thread local storage" hinting at the "next nearest fit" and the comparison with "linearly searching a pool" fails.

    Code:
    GLOBALType * store = /**/;
    TLSType * size[] = /**/;
    TLSType * cache = /**/;
    bool dirty_pool = /**/;
    
    void DoSomething(/**/)
    {
        some_smart_pointer s;
        if(cache->size > (sizeof(int) * 4))
        {
            s = cache->memory;
        }
        else
        {
            void * temp = allSiz[LINE > (sizeof(int) * 4)]->next;
            // update allSiz[LINE > (sizeof(int) * 4)]
            if(!temp)
            {
                // grab more memory for this thread pool
                // or
                // grab this allocation from global
            }
            s = temp;
        }
        // do something
        if(dirty)
        {
            // set cache
            // release cache to thread pool
        }
        else
        {
            // release pool segment to global if $(metric)
            // or
            // release allocation from global
        }
    }
    Yes. This example looks scary expensive compared to a version with `alloca', but with a largely stable process--allocation strategy fits cache metrics--the complexity behind the scenes is largely irrelevant.

    Code:
    GLOBALType * store = /**/;
    TLSType * size[] = /**/;
    TLSType * cache = /**/;
    bool dirty_pool = /**/;
    
    void DoSomething(/**/)
    {
        some_smart_pointer s;
        if(cache->size > (sizeof(int) * 4))
        {
            s = cache->memory;
        }
        // do something
        if(!dirty)
        {
            // do nothing for allocator
            // cache is "warm"
        }
    }
    I'm obviously grossing over a lot of implementation details, but the point is, a lot of modern allocator implementations for C++ do all sorts of nearly magic caching behind the scenes. (The suggestion of manually using "thread pools" from Elysia is an example; a lot of modern allocator designs use the same techniques transparently.) Anything you might try to "add" to the process--including using multiple allocator implementations--will often decrease performance because you aren't following the expected strategy of "lots of small thread specific allocations".

    And if not alloca, how am I supposed to get variable length arrays on the stack in C++ if ISO C++ forbids it?
    As laserlight says, you are already using a compiler extension; using a different compiler extension shouldn't be a problem for you.

    That said, because you are already following a miniscule approach, you may use a manually employ a "double ended stack" which, once created, has almost identical performance to `alloca' with the added benefit of being extremely portable.

    [Edit]
    You use one side of the stack for "this function" and the other side for "that function". So, to allocate as `alloca' you use only the one side while "return values" use the other side.

    Code:
    void Core(/**/)
    {
        // this function needs an array
        DEStack sA(global);
        int * s = sA.get<int>(4);
        // `s' is released automatically
    }
    Code:
    int * Implementation(/**/)
    {
        // the calling function needs an array
        DEStack sA(global);
        int * s = sA.rget<int>(4);
        // ...
        return s;
    }
    
    void Client(/**/)
    {
        DEStack sA(global);
        int * s = Implementation();
        // `s' is released automatically
    }
    [/Edit]

    Be fairly warned, that is an extreme form of "micro-optimization" only to buy a passable form of `alloca'.

    Elysia, I'm having a really hard time admiring you right now.
    You should put your money... over your mouth because you are just ridiculous.

    Software development isn't a popularity context, but at least a few people here already blame you for "chasing off" one regular. Keep up nonsense like that and you may very well find that no one wants to help you anymore.

    [Edit]
    ^_^;

    I love "popularity context" so hard.
    [/Edit]

    You also need to admire microkernel operating systems. Those are a piece of art, unlike monolithic operating systems...
    The modern "Windows" kernels are hybrid designs being truly neither monolithic nor microlithic.

    Soma
    Last edited by phantomotap; 01-23-2014 at 01:53 PM.
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  11. #41
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by phantomotap View Post
    The modern "Windows" kernels are hybrid designs being truly neither monolithic nor microlithic.
    I'm aware of this fact. I didn't imply anywhere that Windows kernel is a piece of art... I don't like it any more than I like Linux's kernel.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #42
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I was totally kidding when I said that about Elysia.

    I'm not sure if this is appropriate to ask in this topic but who did I chase off? I don't think I've ever once insulted anyone's programming ability here. I thought I always showed good respect to other people's ideas and implementations.

    I only said it was hard to admire Elysia because I'm a Linux fanboy and I feel as though I learned a lot from Elysia (I learned a lot from a lot of posters here) and there's some form of looking up to there. I look up to you guys because you're the ones with the experience and the expertise. I learn from you guys and I assumed I had always been respectful and whether you believe it or not, I've always been grateful. But maybe it was a lame joke...

    Unless this is about me making a "your Mom" joke to std in which case, how could that have possibly chased him out? I don't think I've ever made such random/troll-ish posts to any of his programming threads/questions.

    Edit : Sorry, I thought I was having a playful spat with Elysia, pointlessly arguing over which OS is "better" because it's fun to let your fanboy flag fly and just say nonsense. I wasn't genuinely upset and Elysia, I hope you're not either. I don't want to alienate people. I consider this play holy ground. General discussion where everything is off-topic, eh. But the actual programming/tech boards are places of learning and should be safe. I don't want to be seen as hostile.
    Last edited by MutantJohn; 01-23-2014 at 02:14 PM.

  13. #43
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    I'm aware of this fact. I didn't imply anywhere that Windows kernel is a piece of art... I don't like it any more than I like Linux's kernel.
    O_o

    Fair enough, but given your predilection, can you blame me for having so inferred?

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  14. #44
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    I'm not sure if this is appropriate to ask in this topic but who did I chase off?
    Reference: Looking for an overview from the Linux experts.

  15. #45
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Oh man, you're right. I miss Nominal. Did I really get blamed for chasing him off though? Oh, thank God. I was so worried that I had made std scared to post. I haven't seen him make any topics in awhile and I was getting worried. Oh thank God. std, post more. You need to be asking more questions. We're like the same age and experience and we both seem to be into computational geometry.

    I remember that topic, though, and I actually miss Nominal. He was really cool until he got mad at grumpy.

    I take grumpy for what he is. He's pretty smart and seems like he's right. I mean, I'd always go with his answer over mine or at least I'd double check all my answers to his. And Nominal is literally the reason why I can program meshes. I was incredibly grateful to him but the way he was acting, he had a disproportionate reaction. I guess he let his code do the talking for him but the way he was acting was very unbecoming for someone I held in such high regard so I was attempting to tell him to cool it. Then he turned it towards me and lord forbid that he treat me in such a way.

    I was trying to tell him not to get mad over the internet and that he was acting like a giant .......

    Heck, I called phantom that too when I was new here because I wasn't used to him either but he somehow found a way to move on and he was even gracious enough to help me in this topic.

    Truth be told, I'm not sorry for that topic. I mean, I was younger then and just learning to code. I didn't know much but I respected him and I thought he should have respect too because grumpy was fine in that argument. Nominal couldn't control his emotions and he rage quit. I don't like it. I wish he would come back. But that's life.

    If it makes you feel any better though, if some kid shows up asking about meshing, I can do what Nominal did for me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. portable alloca
    By wiglaf in forum C Programming
    Replies: 4
    Last Post: 02-17-2011, 12:34 AM
  2. alloca() function
    By budala in forum C Programming
    Replies: 8
    Last Post: 04-28-2010, 10:09 AM
  3. alloca.h
    By kryptkat in forum C Programming
    Replies: 4
    Last Post: 11-15-2009, 12:34 PM