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)
r = envp;
i = 0;
//how can I add string without using malloc?
// my problem is I can't free this allocated memory
r[i] = malloc(strlen(str));
r[i] = str;
r[++i] = 0;
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
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.