Patchwork [U-Boot,02/12] tools/env: Remove unneeded complexity

login
register
mail settings
Submitter Joe Hershberger
Date Aug. 17, 2012, 8:49 p.m.
Message ID <1345236586-19076-3-git-send-email-joe.hershberger@ni.com>
Download mbox | patch
Permalink /patch/178372/
State Superseded
Delegated to: Tom Rini
Headers show

Comments

Joe Hershberger - Aug. 17, 2012, 8:49 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.

Signed-off-by: Joe Hershberger <joe.hershberger@ni.com>
---
 tools/env/fw_env.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
Mike Frysinger - Aug. 23, 2012, 3:30 a.m.
On Friday 17 August 2012 16:49:36 Joe Hershberger wrote:
> --- a/tools/env/fw_env.c
> +++ b/tools/env/fw_env.c
> 
> -			memset(value, 0, len - strlen(name));
> +			memset(value, 0, len);

side note: this memset is mostly useles as the value buffer largely gets 
written.  all it should be is:
	value[len - 1] = '\0';

similarly, this logic at the end:
	if (value)
		free(value);
that "if" check is pointless as free(NULL) works fine

if you really wanted, the whole loop could be rewritten to use realloc

	for (i = 2; i < argc; ++i) {
		const char *val = argv[i];
		size_t val_len = strlen(val);

		value = realloc(value, len + val_len + 1);
		if (!value) {
			fprintf(...);
			return -1;
		}

		memcpy(value + len, val, val_len);
		len += val_len;
		value[len++] = ' ';
	}
	value[len - 1] = '\0';
-mike

Patch

diff --git a/tools/env/fw_env.c b/tools/env/fw_env.c
index e46791d..a461dbd 100644
--- a/tools/env/fw_env.c
+++ b/tools/env/fw_env.c
@@ -484,22 +484,23 @@  int fw_setenv(int argc, char *argv[])
 
 	name = argv[1];
 
-	len = strlen(name) + 2;
+	len = 0;
 	for (i = 2; i < argc; ++i)
 		len += strlen(argv[i]) + 1;
 
 	/* Allocate enough place to the data string */
 	for (i = 2; i < argc; ++i) {
 		char *val = argv[i];
+
 		if (!value) {
-			value = (char *)malloc(len - strlen(name));
+			value = (char *)malloc(len);
 			if (!value) {
 				fprintf(stderr,
 				"Cannot malloc %zu bytes: %s\n",
-				len - strlen(name), strerror(errno));
+				len, strerror(errno));
 				return -1;
 			}
-			memset(value, 0, len - strlen(name));
+			memset(value, 0, len);
 			tmpval = value;
 		}
 		if (i != 2)