Will Compiler optimize malloc/free or new/delete pair into alloca

Is there any mature C/C++ compiler, capable of optimizing malloc/free (or new/delete) pairs info alloca? In other words, convert from heap-based memory to stack-based (ONLY for some limited cases).

This optimization may be allowed only for pair of malloc/free when both functions are in the same function (or even in the same block of {}), and free is called every time when malloc is called. Also, lets consider that pointer to malloced memory is not saved in some global variable.

So, will GCC/LLVM+clang/Intel Compiler convert such block of code:

{ char *carray; carray = malloc(100); // or malloc(N) // some string-like work with carray free(carray); }


{ char*carray; carray = alloca(100); // or if(N<const1) carray=alloca(N);else carray=malloc(N) // the same work // nothing // or if(N>=const1) free(carray) }

This conversion may be not very useful for every program, but I think, there may be some special compiler option.

PS (update1) We can limit our discussion only to cases when compiler Knows that malloc and free is from libc (stdlib)


In general, no compiler performs this optimization. That's good, because this thing can be potentially very harmful: bear in mind that the stack is usually very limited in its size. If a compiler optimized malloc+free into an alloca, the observable behavior of the code would change: for some inputs, it wouldn't crash with malloc+free, but it would with alloca (because the stack space got exhausted). Therefore, this optimization is unsafe (and illegal according to the standard, because it changes the observable behavior) and compilers don't even try to perform it.

That said, in some very specific circumstances, a compiler could perform it, but no compiler I'm aware of does.

The optimization performed by LLVM and mentioned in the comments is a different thing, it only optimizes out mallocs that are only compared to null and then freed.

There's an off-shoot of LLVM called poolalloc that does this optimization. It's being maintained as part of SAFECode, and isn't in the mainline LLVM distribution.

It's described in Chris Lattner's PhD thesis and in this PLDI paper. The code is here.

Technically, the compilers can optimize anything as long as they follow the As-If rule.
So, optimizing heap allocations to stack allocations would be possible but do to the compiler needs to be intelligent enough to probe the usage and determine that changing the allocation to stack won't affect the observable behavior of the program.

I am not aware of any compiler which does this.

Category:c# Time:2012-04-28 Views:0

Related post

  • Compc (Actionscript Library Compiler) Doesn't Fail Unless I Delete the File First? 2009-01-27

    Here's the scenario: I run compc on a source directory to recompile an already existing library after some changes, which completes successfully. Then I remove the library (the .swc file) and re-compile, which causes many errors to be thrown. Nothing

  • Coding Practices which enable the compiler/optimizer to make a faster program 2010-01-15

    Many years ago, C compilers were not particularly smart. As a workaround K&R invented the register keyword, to hint to the compiler, that maybe it would be a good idea to keep this variable in an internal register. They also made the tertiary ope

  • How-to ensure that compiler optimizations don't introduce a security risk? 2010-09-24

    I have to write a Windows service that handles at some point confidential data (such as PIN codes, passwords, and so on). Those informations are needed for a very short amount of time: usually they are sent almost immediately to a smart card reader.

  • Does compiler optimize inline function's local variables 2012-03-16

    Now I am read the book Inside The C++ Object Model 's fourth section and have some question. An inline function like this: inline int max(int a, int b) { return (a > b) ? a : b; } Then, a statement such as the following: a = max(x, y); this statem

  • Constants and compiler optimization in C++ 2008-10-17

    I've read all the advice on const-correctness in C++ and that it is important (in part) because it helps the compiler to optimize your code. What I've never seen is a good explanation on how the compiler uses this information to optimize the code, no

  • Will the c++ compiler optimize away unused return value? 2008-11-07

    If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never answer.) Elementary example: ReturnValue MyClass::FunctionThatAltersMembersA

  • C++ compiler optimization of passed arguments 2008-11-12

    I'm using a logging module that can have reporting enabled/disabled at runtime. Calls generally go something like: WARN( "Danger Will Robinson! There are " + boost::lexical_cast<string>(minutes) + " minutes of oxygen left!" ); I'm using an inli

  • C++ : Will compiler optimize &Variable; away? 2009-07-17

    In C++ a statement like this is valid: &Variable; IMO it doesn't make any sense, so my question is, if you do this, will it affect the compiled result in any way, or will the compiler optimize it away? Thanks! --------------Solutions-------------

  • how can i disable compiler optimization in c#? 2009-07-29

    how can i disable compiler optimization in c#?? --------------Solutions------------- At the command line (csc), /optimize- In the IDE, project properties -> build -> "optimize code" For some JIT optimizations, you can use [MethodImpl(...)] You

  • compiler optimization implementation 2009-11-14

    Actually I am making a major project in implementing compiler optimization techniques. I already know about the existing techniques, but I am confused what technique to choose and how to implement it. --------------Solutions------------- G'day, What

  • Does Functional programming allow better runtime compiler optimizations? 2009-12-10

    NOTE: Already made this a Wiki. I don't care what this question is tagged as, as long as there is a good discussion. I've heard that since in pure functional programs, there are no side effects and values dont mutate, it makes it easier for the compi

  • Verifying compiler optimizations in gcc/g++ by analyzing assembly listings 2010-01-06

    I just asked a question related to how the compiler optimizes certain C++ code, and I was looking around SO for any questions about how to verify that the compiler has performed certain optimizations. I was trying to look at the assembly listing gene

  • Compiler optimization for fastest possible code 2010-01-14

    I would like to select the compiler optimizations to generate the fastest possible application. Which of the following settings should I set to true? Dead store elimination Eliminate duplicate expressions within basic blocks and functions Enable loop

  • Example of 'volatile' preventing a compiler optimization in C#? 2010-02-19

    From what I understand, the 'volatile' modifier in C# has two effects: Inserts fences as necessary for the target processor Prevents certain compiler optimizations On x86 / amd64, (1) is irrelevant. Those processors don't require fences for volatile

  • .NET compiler optimizations 2010-03-09

    I am writing an application that I need to run at incredibly low processor speeds. The application creates and destroys memory in creative ways throughout its run, and it works just fine. What compiler optimizations occur so I can try to build to tha

  • Visual Studio Question: When doing a compile/debug is VS suppose to delete existing files in the bin\debug area? 2010-03-15

    Q1 - When doing a compile/debug is VS suppose to delete existing files in the bin\debug area? (for VS2008) if no then can I ask please: Q2 - My winforms checks for existance of a sqlite.db3 file and creates it if it needs to (programmatically). If th

  • Can compiler optimization introduce bugs? 2010-04-27

    Today I had a discussion with a friend of mine and we debated for a couple of hours about "compiler optimization". I defended the point that sometimes, a compiler optimization might introduce bugs or at least, undesired behavior. My friend totally di

  • Compiler optimization causing the performance to slow down 2010-04-29

    I have one strange problem. I have following piece of code: template<clss index, class policy> inline int CBase<index,policy>::func(const A& test_in, int* srcPtr ,int* dstPtr) { int width = test_in.width(); int height = test_in.height

  • Java Compiler: Optimization of "cascaded" ifs and best practices? 2010-05-19

    Does the Java Compiler optimize a statement like this if (a == true) { if (b == true) { if (c == true) { if(d == true) { //code to process stands here } } } } to if (a == true && b==true && c==true && d == true) So that's my f

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.522 (s). 13 q(s)