bdem
bdem

Reputation: 105

random_seed in gfortran leads to memory leak?

Valgrind reports blocks that are still reachable when using the random_seed routine. Is it expected, is it a bug in gfortran, or am I missing something ?

For instance, the following program, when compiled with gfortran:

rng.f90

program rng
  implicit none

  integer :: n

  call random_seed(size=n)
end program rng

leads to the following report by valgrind:

==233092== 40 bytes in 1 blocks are still reachable in loss record 1 of 1
==233092==    at 0x484A464: calloc (vg_replace_malloc.c:1328)
==233092==    by 0x4893EF6: _gfortrani_xcalloc (memory.c:78)
==233092==    by 0x4AF0DCE: get_rand_state (random.c:248)
==233092==    by 0x4AF0DCE: get_rand_state (random.c:238)
==233092==    by 0x4AF0DCE: _gfortran_random_seed_i4 (random.c:889)
==233092==    by 0x401168: MAIN__ (in /home/baptiste/dev/misc/f90/rng/rng)
==233092==    by 0x40119F: main (in /home/baptiste/dev/misc/f90/rng/rng)
==233092== 
==233092== LEAK SUMMARY:
==233092==    definitely lost: 0 bytes in 0 blocks
==233092==    indirectly lost: 0 bytes in 0 blocks
==233092==      possibly lost: 0 bytes in 0 blocks
==233092==    still reachable: 40 bytes in 1 blocks
==233092==         suppressed: 0 bytes in 0 blocks
==233092== 

gfortran version: GNU Fortran (GCC) 12.2.1 20220819 (Red Hat 12.2.1-2)

I compiled the program above using: gfortran -o rng rng.f90

Upvotes: 3

Views: 131

Answers (1)

janneb
janneb

Reputation: 37198

This is (minor) bug somewhere, potentially in how valgrind handles stuff like thread destructors. In GFortran each thread has it's own PRNG state, which is allocated lazily the first time it's needed, and then freed by the thread destructor.

See https://gcc.gnu.org/git?p=gcc.git;a=blob;f=libgfortran/intrinsics/random.c;h=b5732e6c25a14359745c5f698c2dd4cab6f3c81f;hb=HEAD#l238 for the get_rand_state() function which the various higher level routines use to access the PRNG state, and https://gcc.gnu.org/git?p=gcc.git;a=blob;f=libgfortran/intrinsics/random.c;h=b5732e6c25a14359745c5f698c2dd4cab6f3c81f;hb=HEAD#l1034 for the constructor and destructor functions.

Upvotes: 3

Related Questions