How do I correctly allocate heap memory in a function so its caller can use the pointer passed in? For example:
#include <stdlib.h>
#include <string.h>
void test(char *arg) {
arg = malloc(3);
strcpy(arg,"hi");
}
int main() {
char *x = NULL;
test(x);
printf("%s\n",x); //should print "hi", instead does nothing
return 0;
}
I have also tried to use strdup
but cannot get main to correctly print the string I assign the pointer to in the test function, but I always get garbage data or a segfault.
To be clear, I cannot modify the signature of test
in any way, so double pointers or returning a pointer are not valid solutions. It is possible to return a different string using a char*
argument?)