[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

rb_str_new2, malloc, free - core dump

djberg96

3/3/2005 9:48:00 PM

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

1 Answer

Charles Mills

3/3/2005 10:16:00 PM

0


Daniel Berger wrote:
> 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