https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62112
Bug ID: 62112 Summary: Optimize out malloc when block is unused or write-only Product: gcc Version: 4.9.1 Status: UNCONFIRMED Keywords: missed-optimization Severity: enhancement Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: zackw at panix dot com This program #include <string.h> #include <stdlib.h> int main(void) { size_t n = 1000; float *x = calloc(n,sizeof(float)); float *y = malloc(n*sizeof(float)); if (x && y) memcpy(y,x,sizeof(float)*n); return 0; } can be optimized (in the absence of `-fno-builtin-(memcpy|malloc|calloc)`) to int main(void) { return 0; } because: the memory block pointed to by `y` is write-only, so the `memcpy` and `malloc` can be discarded; after that is done, the memory block pointed to by `x` is unused, so that allocation can be discarded as well. `calloc` is used here to avoid any question of UB due to reading uninitialized memory even within `memcpy`. The optimization should apply to all heap-allocation functions, including especially C++ operator new (as long as the constructor has no side effects outside the just-allocated object). Clang 3.5 does perform this optimization.