In the following code, I pass a pointer by value to a function I'm hoping to have concatenate N strings onto the original one.
In the way I've written it, I'm allocating new memory by working out how many bytes to add onto the original string length.
This new string is then populated and the pointer to that string is returned.
So, let's say the original pointer msg is 0x000001, and it points to the starting char of the string "Hello\0".
Then in the function, a new pointer strNew eventually points to "Hello world, poop\0", and has a value of 0x0000f5, where that new string's memory is located.
Then, as a return of the function the msg pointer's value is now 0x0000f5.
My question is, what happens to the memory located at 0x000001?? It contains bytes for "Hello\0", but there is no longer a pointer to it. Does it get garbage collected? Is it a problem? Should I overwrite the contents somehow with ' ' chars?
If not, how do I free it from within the strcatcat() function?
The idea is to not have to worry about having a character array large enough for the strings to begin with. Is this unreasonable?
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
char * strcatcat(char * orig, const char* strArgs, ...){
va_list valist;
unsigned long initStrLength = strlen(orig);
// work out how much me to realloc
unsigned long moreBytes = 0;
va_start(valist, strArgs);
const char* str = strArgs;
while (str != NULL ) {
moreBytes += strlen(str);
str = va_arg(valist, const char *);
}
// define a new char pointer to populate, of defined size
char * strNew = NULL;
strNew = (char *) malloc((moreBytes + initStrLength+1));
// copy the original string into the start
strcpy(strNew, orig);
//reset, then go through and concat into new string
va_start(valist, strArgs);
str = strArgs;
while (str != NULL ) {
strcat(strNew, str);
str = va_arg(valist, const char *);
}
// close list
va_end(valist);
// return this pointer
return strNew;
}
int main()
{
char * msg = "Hello";
msg = strcatcat(msg, " World, ", "poop", NULL);
printf("%s\n", msg);
return 0;
}
Edit: Thanks all, that has cleared it up. I'm used to higher level langs like PHP, C# etc and reading about pointer arithmetic this question popped up that I couldn't find an answer that wasn't focused on the pointer rather than the value of the pointer.
TLDR for people in the future - without the caller managing it, the example I gave would cause a memory leak. The pointer inside main would need copying so as to deallocate.