[前][次][番号順一覧][スレッド一覧]

ruby-changes:38431

From: nobu <ko1@a...>
Date: Sat, 16 May 2015 21:57:33 +0900 (JST)
Subject: [ruby-changes:38431] nobu:r50512 (trunk): ifaddr.c: wrapper object before alloc

nobu	2015-05-16 21:57:17 +0900 (Sat, 16 May 2015)

  New Revision: 50512

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=50512

  Log:
    ifaddr.c: wrapper object before alloc
    
    * ext/socket/ifaddr.c (rsock_getifaddrs): make wrapper object
      before result structs allocation and manage refcount for each
      elements to get rid of potential memory leak.

  Modified files:
    trunk/ext/socket/ifaddr.c
Index: ext/socket/ifaddr.c
===================================================================
--- ext/socket/ifaddr.c	(revision 50511)
+++ ext/socket/ifaddr.c	(revision 50512)
@@ -98,7 +98,7 @@ rsock_getifaddrs(void) https://github.com/ruby/ruby/blob/trunk/ext/socket/ifaddr.c#L98
     int numifaddrs, i;
     struct ifaddrs *ifaddrs, *ifa;
     rb_ifaddr_root_t *root;
-    VALUE result;
+    VALUE result, addr;
 
     ret = getifaddrs(&ifaddrs);
     if (ret == -1)
@@ -112,8 +112,10 @@ rsock_getifaddrs(void) https://github.com/ruby/ruby/blob/trunk/ext/socket/ifaddr.c#L112
     for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next)
         numifaddrs++;
 
+    addr = TypedData_Wrap_Struct(rb_cSockIfaddr, &ifaddr_type, 0);
     root = xmalloc(sizeof(rb_ifaddr_root_t) + (numifaddrs-1) * sizeof(rb_ifaddr_t));
-    root->refcount = root->numifaddrs = numifaddrs;
+    root->refcount = 0;
+    root->numifaddrs = numifaddrs;
 
     ifa = ifaddrs;
     for (i = 0; i < numifaddrs; i++) {
@@ -122,10 +124,15 @@ rsock_getifaddrs(void) https://github.com/ruby/ruby/blob/trunk/ext/socket/ifaddr.c#L124
         root->ary[i].root = root;
         ifa = ifa->ifa_next;
     }
+    RTYPEDDATA_DATA(addr) = &root->ary[0];
+    root->refcount++;
 
     result = rb_ary_new2(numifaddrs);
-    for (i = 0; i < numifaddrs; i++) {
-        rb_ary_push(result, TypedData_Wrap_Struct(rb_cSockIfaddr, &ifaddr_type, &root->ary[i]));
+    rb_ary_push(result, addr);
+    for (i = 1; i < numifaddrs; i++) {
+	addr = TypedData_Wrap_Struct(rb_cSockIfaddr, &ifaddr_type, &root->ary[i]);
+	root->refcount++;
+	rb_ary_push(result, addr);
     }
 
     return result;

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]