rb_str_new2, malloc, free - core dump

D

Daniel Berger

Hi all,

Ruby 1.8.2
Solaris 9
gcc 3.4.2

The following function core dumps when I test it on Solaris (though
Windows XP with VC++ 7.0 does not complain). However, it seems to work
fine if I remove the call to free().

Should I not malloc() the char pointer in the first place? I
originally did this to silence -Wall. Is there still some connection
between 'rbName' and 'name' after the call to rb_str_new2()? Why would
calling free() causing a core dump?

static VALUE bar_test(VALUE klass){
VALUE rbName;
char* name;
name = malloc(128);
name = getenv("USER");
rbName = rb_str_new2(name);
free(name);
return rbName;
}

Note that I don't want to just remove free(), for fear of a memory
leak.

Regards,

Dan
 
C

Charles Mills

Daniel said:
Hi all,

Ruby 1.8.2
Solaris 9
gcc 3.4.2

The following function core dumps when I test it on Solaris (though
Windows XP with VC++ 7.0 does not complain). However, it seems to work
fine if I remove the call to free().

Should I not malloc() the char pointer in the first place? I
originally did this to silence -Wall. Is there still some connection
between 'rbName' and 'name' after the call to rb_str_new2()? Why would
calling free() causing a core dump?

static VALUE bar_test(VALUE klass){
VALUE rbName;
char* name;
name = malloc(128);

/* name points to an allocated chunck of 128 bytes */
name = getenv("USER");

/* name points to the return value of getenv
* this is a memory leak - previous chunk is now lost */
rbName = rb_str_new2(name);
free(name);

/* you free name - your not suppost to do this (see man getenv) */
return rbName;
}

Note that I don't want to just remove free(), for fear of a memory
leak.

Also getenv returns a null pointer if the environmental variable is not
set. You should check for this.
Try this:
static VALUE bar_test(VALUE klass){
char*name = getenv("USER");
if (name == NULL) return Qnil;
return rb_str_new2(name);
}

-Charlie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top