Allocate the correct amount of memory when escaping a string

This commit is contained in:
Cary R 2017-01-08 20:44:17 -08:00
parent bb91512e75
commit 561638a31f
1 changed files with 5 additions and 5 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003-2016 Stephen Williams (steve@icarus.com) * Copyright (c) 2003-2017 Stephen Williams (steve@icarus.com)
* *
* This source code is free software; you can redistribute it * This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU * and/or modify it in source code form under the terms of the GNU
@ -37,17 +37,17 @@ PLI_UINT64 timerec_to_time64(const struct t_vpi_time*timerec)
char *as_escaped(char *arg) char *as_escaped(char *arg)
{ {
unsigned idx, cur, cnt, len = strlen(arg); unsigned idx, cur, cnt, len = strlen(arg) + 1;
char *res = (char *) malloc(sizeof(char *) * len); char *res = (char *) malloc(sizeof(char) * len);
cur = 0; cur = 0;
cnt = len; cnt = len - 1;
for (idx = 0; idx < cnt; idx++) { for (idx = 0; idx < cnt; idx++) {
if (isprint((int)arg[idx])) { if (isprint((int)arg[idx])) {
res[cur] = arg[idx]; res[cur] = arg[idx];
cur += 1; cur += 1;
} else { } else {
len += 3; len += 3;
res = (char *) realloc(res, sizeof(char *) * len); res = (char *) realloc(res, sizeof(char) * len);
sprintf(&(res[cur]), "\\%03o", arg[idx]); sprintf(&(res[cur]), "\\%03o", arg[idx]);
cur += 4; cur += 4;
} }