nonoob's suggestion is a correct one and Elysia's assertion is certainly right, but if you integrate Elysia's example into your code, you would then be returning a pointer to a local variable, which is wrong. Rather, one might write:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *getString(void);
int main(void) {
char *test = getString();
printf("%s\n", test);
free(test);
return 0;
}
char *getString(void) {
char *test = malloc(20 * sizeof(*test));
strcpy(test, "this is a string");
return test;
}
Observe that the correct headers were included, and that I removed the cast of the return value of malloc. Furthermore, sizeof(char) is always 1, so you could leave it out, but I chose to change it to the more general sizeof(*test).
EDIT:
Additionally, one should check that malloc did not return a null pointer before accessing the memory presumed to be allocated.