[U-Boot,v2,2/5] tools/env: Remove unneeded complexity

Submitted by Joe Hershberger on Oct. 3, 2012, 7:38 p.m.

Details

Message ID 1349293130-5715-3-git-send-email-joe.hershberger@ni.com
State Accepted
Delegated to: Tom Rini
Headers show

Commit Message

Joe Hershberger Oct. 3, 2012, 7:38 p.m.
The length included the name length, and then it was subtracted back
out on each use.  Now we don't include it in the first place.  Also
realloc as we process arguments and eliminate memset.  Use memcpy
instead of manually copying each byte.

Signed-off-by: Joe Hershberger <joe.hershberger@ni.com>
---
Changes in v2:
- Further simplified based Mike's comments

 tools/env/fw_env.c | 33 +++++++++++++--------------------
 1 file changed, 13 insertions(+), 20 deletions(-)

Patch hide | download patch | download mbox

diff --git a/tools/env/fw_env.c b/tools/env/fw_env.c
index 16073ea..af879f1 100644
--- a/tools/env/fw_env.c
+++ b/tools/env/fw_env.c
@@ -481,7 +481,6 @@  int fw_setenv(int argc, char *argv[])
 	int i, len;
 	char *name;
 	char *value = NULL;
-	char *tmpval = NULL;
 
 	if (argc < 2) {
 		errno = EINVAL;
@@ -495,34 +494,28 @@  int fw_setenv(int argc, char *argv[])
 
 	name = argv[1];
 
-	len = strlen(name) + 2;
-	for (i = 2; i < argc; ++i)
-		len += strlen(argv[i]) + 1;
-
-	/* Allocate enough place to the data string */
+	len = 0;
 	for (i = 2; i < argc; ++i) {
 		char *val = argv[i];
+		size_t val_len = strlen(val);
+
+		value = realloc(value, len + val_len + 1);
 		if (!value) {
-			value = (char *)malloc(len - strlen(name));
-			if (!value) {
-				fprintf(stderr,
+			fprintf(stderr,
 				"Cannot malloc %zu bytes: %s\n",
-				len - strlen(name), strerror(errno));
-				return -1;
-			}
-			memset(value, 0, len - strlen(name));
-			tmpval = value;
+				len, strerror(errno));
+			return -1;
 		}
-		if (i != 2)
-			*tmpval++ = ' ';
-		while (*val != '\0')
-			*tmpval++ = *val++;
+
+		memcpy(value + len, val, val_len);
+		len += val_len;
+		value[len++] = ' ';
 	}
+	value[len - 1] = '\0';
 
 	fw_env_write(name, value);
 
-	if (value)
-		free(value);
+	free(value);
 
 	return fw_env_close();
 }