I am trying to pass a literal to a function, assign it to struct and use it later. Do I have to malloc()
and strcpy()
, or can I save the char*
for use later (does it get statically allocated or not)?
Minimalistic example code below:
struct data {
char *string;
...;
}
struct data *create_data(char *input_string, ...) {
struct data *result = malloc(sizeof(struct data));
result->string = input_string;
return result;
}
struct data *string = create_data("Hey", ...);
printf("%s", data->string);
or
struct data *create_data(char *input_string, ...) {
struct data *result = malloc(sizeof(struct data));
result->string = malloc(sizeof(input_string));
strcpy(result->string, input_string);
return result;
}
struct data *string = create_data("Hey",...);
printf("%s", data->string);
Can I expect the first one to work, so the data in memory wouldn't get overwritten, or is it unsafe to assume so?