Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix leak reported by Valgrind when setting environment variables #10689

Merged
merged 1 commit into from May 1, 2024

Conversation

peterzhu2118
Copy link
Member

The call to setenv replaces the string in the environ array, which causes the original string to be reported as a memory leak.

This commit allocates another copy of environ called alloc_environ that contains the strings allocated by ruby_init_setproctitle. Then in ruby_free_proctitle it frees all the strings in alloc_environ.

For example:

ENV.each { |k, v| ENV[k] = v.dup }

Valgrind reports:

3,321 bytes in 39 blocks are definitely lost in loss record 3 of 3
  at 0x484884F: malloc (vg_replace_malloc.c:393)
  by 0x25CB5B: objspace_xmalloc0 (gc.c:11972)
  by 0x40344E: ruby_strdup (util.c:540)
  by 0x59C854: ruby_init_setproctitle (setproctitle.c:143)
  by 0x38CC44: ruby_process_options (ruby.c:3101)
  by 0x234DB1: ruby_options (eval.c:117)
  by 0x15B92E: rb_main (main.c:40)
  by 0x15B92E: main (main.c:59)

The call to setenv replaces the string in the environ array, which causes
the original string to be reported as a memory leak.

This commit allocates another copy of environ called alloc_environ that
contains the strings allocated by ruby_init_setproctitle. Then in
ruby_free_proctitle it frees all the strings in alloc_environ.

For example:

    ENV.each { |k, v| ENV[k] = v.dup }

Valgrind reports:

    3,321 bytes in 39 blocks are definitely lost in loss record 3 of 3
      at 0x484884F: malloc (vg_replace_malloc.c:393)
      by 0x25CB5B: objspace_xmalloc0 (gc.c:11972)
      by 0x40344E: ruby_strdup (util.c:540)
      by 0x59C854: ruby_init_setproctitle (setproctitle.c:143)
      by 0x38CC44: ruby_process_options (ruby.c:3101)
      by 0x234DB1: ruby_options (eval.c:117)
      by 0x15B92E: rb_main (main.c:40)
      by 0x15B92E: main (main.c:59)
@peterzhu2118 peterzhu2118 merged commit d1f14ba into ruby:master May 1, 2024
101 checks passed
@peterzhu2118 peterzhu2118 deleted the free-environ branch May 1, 2024 12:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants