You should pass it as a pointer to a pointer:
void set(char **buf) { *buf = malloc(5 * sizeof(char)); strcpy(*buf, "test"); }
Name it as follows:
char *str; set(&str); puts(str); free(str);
Note that I changed the call to malloc to highlight five characters, because you only select the actual characters, but the line also contains a special terminator character, and you also need a place for that.
I also use strcpy to copy the string to the allocated memory. This is because you rewrite the pointer differently, that is, you lose the pointer that you select and will have a memory leak.
You should also remember the free pointer when you finish with it, or the memory will remain allocated until the program ends.
Some programmer dude
source share