char full_name[] = "foo boo";
char * full_name = "foo boo";
从安全角度来看,每个选项的优缺点是什么?
处理c字符串是一项复杂的任务,您展示的选项没有任何优缺点。这实际上取决于您想要实现的解决方案。
char full_name[] = "foo boo";
是一个具有以下内容的数组
{'f', 'o', 'o', ' ', 'b', 'o', 'o', '\0'}
你可以修改它,但它不能增长,而且
char *full_name = "foo boo";
是一个字符串字面量,你不能修改它也不能让它增长,最好像这样定义
const char *full_name = "foo boo";
char *full_name = "foo boo";
将字面值赋给变量(用字面值初始化变量)。您无法更改字面字符串,但可以将另一个字面值或变量分配给该变量,例如 full_name = my_name;
。 - Paul Ogilviechar *full_name;
是一个指针变量,因此您可以将不同(其他)变量分配给它。 它们可以是文字,也可以是包含从文件中读取的字符串的 malloc
缓冲区。 这不是 UB。 - Paul Ogilviechar *full_name
实际上是一个指针,因此可以重新分配它。这是使用 const
的另一个原因,即使你使用 const
进行 full_name = malloc(some_size)
,你仍需要显式地转换掉 const
,以最小化更改字符串字面量的潜在 未定义行为
。例如 const char *full_name = "Something"; if (something_else == true) {full_name = strdup("Something Else");} free(full_name);
将至少发出警告。请注意,如果 something_else == false
-> 未定义行为。 - Iharob Al Asimichar str[4] = "GfG"; /*One extra for string terminator*/
/* OR */
char str[4] = {‘G’, ‘f’, ‘G’, '\0'}; /* '\0' is string terminator */
str[]
是一个auto variable,那么字符串将存储在stack segment
中,如果它是一个global
或static
变量,则存储在data segment中等。
使用字符指针的字符串
使用字符指针
,字符串可以以两种方式存储:
Read-only string in a shared segment.
When string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read only block (generally in data segment
) that is shared among functions.
char *str = "GfG";
In the above line “GfG”
is stored in a shared read-only location, but pointer str
is stored in a read-write memory. You can change str
to point something else but cannot change value at present str
. So this kind of string should only be used when we don’t want to modify string at a later stage in program.
Dynamically allocated in heap segment
.
Strings are stored like other dynamically allocated things in C
and can be shared among functions.
char *str;
int size = 4; /*one extra for ‘\0’*/
str = malloc(size);
*(str+0) = 'G';
*(str+1) = 'f';
*(str+2) = 'G';
*(str+3) = '\0';
QString
。因此,在C++中,指针仍然非常重要。 - Iharob Al Asimi