------- Comment #5 from fxcoudert at gcc dot gnu dot org 2007-03-18 23:03 ------- When creating a testcase for this one, I found we have a similar problem with character functions:
$ cat a.f90 program test print *, len(bar(-1)) contains function bar(i) integer, intent(in) :: i character(len=i) :: bar bar = "" end function bar end program test $ gfortran a.f90 && ./a.out Fortran runtime error: Attempt to allocate a negative amount of memory. Complete patch is: Index: trans-expr.c =================================================================== --- trans-expr.c (revision 123028) +++ trans-expr.c (working copy) @@ -227,6 +227,8 @@ gfc_init_se (&se, NULL); gfc_conv_expr_type (&se, cl->length, gfc_charlen_type_node); + se.expr = fold_build2 (MAX_EXPR, gfc_charlen_type_node, se.expr, + build_int_cst (gfc_charlen_type_node, 0)); gfc_add_block_to_block (pblock, &se.pre); tmp = cl->backend_decl; @@ -2256,6 +2258,8 @@ } else { + tree tmp; + /* Calculate the length of the returned string. */ gfc_init_se (&parmse, NULL); if (need_interface_mapping) @@ -2264,7 +2268,11 @@ gfc_conv_expr (&parmse, sym->ts.cl->length); gfc_add_block_to_block (&se->pre, &parmse.pre); gfc_add_block_to_block (&se->post, &parmse.post); - cl.backend_decl = fold_convert (gfc_charlen_type_node, parmse.expr); + + tmp = fold_convert (gfc_charlen_type_node, parmse.expr); + tmp = fold_build2 (MAX_EXPR, gfc_charlen_type_node, tmp, + build_int_cst (gfc_charlen_type_node, 0)); + cl.backend_decl = tmp; } /* Set up a charlen structure for it. */ -- http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31203