Reputation: 89
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?
Upvotes: 3
Views: 71
Reputation: 133879
The string literals have static storage duration. For such an object, C11 6.2.4p3 says that:
Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
And of lifetime C11 6.2.4p2
- The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
I.e. you can safely store a pointer to a string literal for the remainder of program execution.
However, attempts to free
a string literal will have undefined behaviour, so if you sometimes use a string literal and sometimes a malloc
ated string, you need to either keep track of it, or use your 2nd alternative for all cases.
And since string literals are immutable, you must copy them if you intend to modify the string.
Finally, malloc(sizeof(input_string))
is wrong, it must be malloc(strlen(input_string) + 1)
. For duplicating a string, POSIX has the strdup
function.
Upvotes: 5