Project

General

Profile

Actions

Bug #11626

closed

fprintf in c extension keep adding memory usage

Bug #11626: fprintf in c extension keep adding memory usage

Added by ygc (GC Yang) about 10 years ago. Updated about 10 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:71231]

Description

fprintf will keep adding memory usage without releasing it.

I was doing it in rails console, not sure if it makes any different. The code like this:

VALUE leak (VALUE self, VALUE in) {
  char *str = StringValuePtr(in);
  char *pstr;
  pstr = malloc (10240);
  strcat(pstr,str);
  fprintf (stdout, pstr);
  self = rb_str_new_cstr(pstr);
  free (pstr);
  return self;
}

void Init_extension(){
  rb_define_global_function("leak", leak, 1);
}
100000000.times{leak("lots of garbage")}

without the fprintf line the memory usage is normal, adding that line just keep adding memory, kill the console process will release the memory.

If I do 100000.times{Process.wait(fork{ stuff})}, memory also looks normal. Leaking somewhere????

Updated by normalperson (Eric Wong) about 10 years ago Actions #1 [ruby-core:71232]

wrote:

fprintf will keep adding memory usage without releasing it.

I was doing it in rails console, not sure if it makes any different. The code like this:

VALUE leak (VALUE self, VALUE in) {
  char *str = StringValuePtr(in);
  char *pstr;
  pstr = malloc (10240);
  strcat(pstr,str);

pstr is uninitialized memory when you call strcat on it,
likely screwing with how fprintf uses it.
Does replacing the malloc + strcat with:

pstr = strdup(str);

help at all?

  fprintf (stdout, pstr);
  self = rb_str_new_cstr(pstr);
  free (pstr);
  return self;
}

Updated by nobu (Nobuyoshi Nakada) about 10 years ago Actions #2 [ruby-core:71235]

  • Description updated (diff)
  • Status changed from Open to Rejected

Nothing related to ruby, you just collapse the heap by repeatedly appending strings to the same area.
It will depend on the platform, if malloc returns the same pointer as just freed.

Updated by ygc (GC Yang) about 10 years ago Actions #3 [ruby-core:71252]

Nobuyoshi Nakada wrote:

Nothing related to ruby, you just collapse the heap by repeatedly appending strings to the same area.
It will depend on the platform, if malloc returns the same pointer as just freed.

Got it, I should have set the pointer to NULL. Commenting out fprintf works fine made me think it is leaking somehow.

Updated by nobu (Nobuyoshi Nakada) about 10 years ago Actions #4 [ruby-core:71269]

GC Yang wrote:

Got it, I should have set the pointer to NULL.

No, you should not depend on the content of malloced buffer.

Actions

Also available in: PDF Atom