gpt4 book ai didi

我可以在函数结束后保存(和使用)传递给函数的 char* 文字吗?

转载 作者:太空狗 更新时间:2023-10-29 16:00:14 25 4
gpt4 key购买 nike

我正在尝试将文字传递给函数,将其分配给结构并在以后使用。我是否必须 malloc()strcpy(),或者我是否可以保存 char* 供以后使用(它是静态分配的还是不是)?

下面的简约示例代码:

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);

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);

我能否期望第一个工作正常,这样内存中的数据就不会被覆盖,或者这样假设是不安全的?

最佳答案

字符串文字具有静态存储持续时间。对于这样的对象,C11 6.2.4p3说:

Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

和生命周期C11 6.2.4p2

  1. 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.

即您可以安全地存储指向字符串文字的指针,以供程序执行的其余部分使用。


但是,尝试free 一个字符串文字将有未定义的行为,所以如果你有时使用一个字符串文字,有时一个 malloc 化的字符串,你需要要么保持跟踪它,或在所有情况下使用您的第二个替代方案。

并且由于字符串文字是不可变的,如果您打算修改字符串,则必须复制它们。


最后,malloc(sizeof(input_string))是错误的,一定是 malloc(strlen(input_string) + 1)。对于复制字符串,POSIX 有 strdup function .

关于我可以在函数结束后保存(和使用)传递给函数的 char* 文字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55986196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com