If you want to malloc inside the function, you need to pass the address to the outside pointer since ch
inside the function is only a local variable, and changing it doesn't affect the outside cm
variable
void build(char **ch){
*ch = malloc(30*sizeof(char));
strcpy(*ch, "I am a good guy");
}
void main(){
char *cm;
build(&cm);
printf("%s\n", cm);
}
But better don't malloc
inside the function, instead just write what you want to the area pointed to by the pointer. This is the common way when you need to provide a buffer to get data in C. In this way users will have the choice to allocate memory their own, or just use a local buffer and don't need to free memory after that like you've just forgotten in your example
void build(char *ch){
strcpy(ch, "I am a good guy");
}
void main(){
char *cm1;
cm1 = malloc(30*sizeof(char));
build(cm1);
printf("%s\n", cm1);
char cm2[30];
build(cm2);
printf("%s\n", cm2);
free(cm1); // don't forget this
}