First off, C (and C++) is not dynamic like you know it from Java, C#, PHP and others. When you are presented with a string in C, the string is pretty much static in length.
To make the answer simpler, lets redefine your variables:
g->db_cmd
will be called dest
,
l->db.param_value.val
will be called src
, and
l->db.param_value.len
will be called len
.
You should allocate a new string of size len
plus one (for the extra null).
Allocate a new dest
:
dest = calloc(sizeof(char), len + 1);
calloc allocates an array of chars as long as len
plus one. After calloc() has allocated the array it fills it with nulls (or \0) thus you automatically will have a null appended to your dest
string.
Next, copy the src
to dest
with strncpy:
strncpy(dest, src, len);
To convert this back to your variable names:
g->db_cmd = calloc(sizeof(char), l->db.param_value.len + 1);
strncpy(g->db_cmd, l->db.param_value.val, l->db.param_value.len);