Fortran fixes double free in ASSOCIATE with allocatable character functions
GCC Fortran now prevents double-free errors when an `ASSOCIATE` construct uses an allocatable, deferred-length character function as a selector by restricting…
This commit fixes a double-free bug in the GCC Fortran compiler when an ASSOCIATE construct’s selector is an allocatable, deferred-length character function. Previously, an extra free operation was unconditionally applied, but this is only necessary for POINTER-valued character functions. The fix ensures that the extra free is only performed when a POINTER is involved, preventing memory corruption, as allocatable function results are already released by their own cleanup routines.
In Details
The Fortran ASSOCIATE construct can bind a name to a selector, which can be the result of a function call. For character functions returning deferred-length, the trans_associate_var routine in trans-stmt.cc had an unconditional extra free of the associate-name's backend decl. This extra free was introduced for POINTER-valued character functions (PR60458) because their results are not otherwise freed. However, when the function returns an ALLOCATABLE character, the result temporary is already handled by the procedure call's cleanup. This commit restricts the extra free to only `POI…
For Context
In programming, a 'double free' error occurs when a program tries to release the same piece of memory twice, which can lead to crashes or security vulnerabilities. In Fortran, the ASSOCIATE statement lets you give a temporary name to a variable or the result of a function. When a Fortran function returns text (a 'character' type) that can change in length ('allocatable, deferred-length'), the compiler normally takes care of cleaning up that memory. However, there was a bug where if you used such a function with ASSOCIATE, the compiler would try to free that memory an extra time, causing a 'double free'. This fix ensures that the compiler only frees the memory once, preventing these crashes and making Fortran programs more stable.