julekgwa julekgwa - 2 months ago 41
C Question

how to add a string at the end of pointer to pointer (**pointer) in C

I'm trying to add a string at the end of pointer to pointer in C, I'm using the below code the problem is I can't free what I have allocated as the pointer to pointer has values that were not all allocated memory, How can I add string at the end of a pointer to pointer properly?

int add_environ(char *str, char **envp)
{
char **r;
int i;

r = envp;
i = 0;
while (r[i])
{
i++;
}
//how can I add string without using malloc?
// my problem is I can't free this allocated memory
r[i] = malloc(strlen(str));
if (r[i])
{
r[i] = str;
r[++i] = 0;
return (1);
}
return (0);
}

Answer

If your question only targets environmental variables, then I would go with setenv. If not, Waxrat gave you one solution. Oh, btw: You're assuming in your code, that envp is arbitrarily long. That's not true either, so your code will crash sooner or later. Depending on your exact requirements, I would suggest to create a deep copy of envp in main and then only operate on that copy, because then everything is malloced and needs to be freed, so nothing special to track any longer.