libnl_2: Fix memory leaks

BUG: b/5532633

Change-Id: I271168764e26dc465d2442f5015338a3e9a479b8
Signed-off-by: Dmitry Shmidt <dimitrysh@google.com>
diff --git a/libnl_2/netlink.c b/libnl_2/netlink.c
index cc2f88e..ee3d600 100644
--- a/libnl_2/netlink.c
+++ b/libnl_2/netlink.c
@@ -59,15 +59,14 @@
 {
 	int rc = -1;
 	int sk_flags;
-	int RECV_BUF_SIZE;
+	int RECV_BUF_SIZE = getpagesize();
 	int errsv;
 	struct iovec recvmsg_iov;
 	struct msghdr msg;
 
 	/* Allocate buffer */
-	RECV_BUF_SIZE = getpagesize();
 	*buf = (unsigned char *) malloc(RECV_BUF_SIZE);
-	if (!buf) {
+	if (!(*buf)) {
 		rc = -ENOMEM;
 		goto fail;
 	}
@@ -91,8 +90,11 @@
 	errsv = errno;
 	fcntl(sk->s_fd, F_SETFL, sk_flags);
 
-	if (rc < 0)
+	if (rc < 0) {
 		rc = -errsv;
+		free(*buf);
+		*buf = NULL;
+	}
 
 fail:
 	return rc;
@@ -108,7 +110,6 @@
 	int rc, cb_rc = NL_OK, done = 0;
 
 	do {
-
 		unsigned char *buf;
 		int i, rem, flags;
 		struct nlmsghdr *nlh;
@@ -127,7 +128,7 @@
 
 			/* Check for callbacks */
 
-			msg = (struct nl_msg *)malloc(sizeof(struct nl_msg));
+			msg = (struct nl_msg *) malloc(sizeof(struct nl_msg));
 			memset(msg, 0, sizeof(*msg));
 			msg->nm_nlh = nlh;
 
@@ -187,7 +188,6 @@
 			if (done)
 				break;
 		}
-
 		free(buf);
 		buf = NULL;
 
@@ -197,7 +197,7 @@
 
 success:
 fail:
-	return	rc;
+	return rc;
 }
 
 /* Send raw data over netlink socket */