Consider the following program fragment:

  char *p;
  int i;

  for (i=0; i<10; i++)
    {
      p = malloc(20);
      foo(p,i);
      free(p);
    }
}

The loop could be simplified into

  p = malloc(20);
  for (i=0; i<10; i++)
    foo(p,i);

  free(p);

This would reduce the overhead for memory allocation
considerably.

A more challenging case is to change

  for (i=0; i<10; i++)
    {
      p = malloc(2*i+2);
      foo(p,i);
      free(p);
    }

into

  p = malloc(20);
  for (i=0; i<10; i++)
      foo(p,i);

  free(p);

because the amount of memory allocated has an upper bound.

This is probably not a big win for straight C code.  For languages
which generate temporary arrays at runtime, such as Fortran, it
could mean a significant reduction in memory management overhead.

-- 
           Summary: move memory allocation out of a loop
           Product: gcc
           Version: 4.1.0
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P2
         Component: tree-optimization
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: tkoenig at gcc dot gnu dot org
                CC: gcc-bugs at gcc dot gnu dot org


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=21046

Reply via email to