我正在阅读常见的 C 陷阱并在 some famous Uni website 上找到这篇文章. (这是谷歌上出现的第二个链接)。
该页面上的最后一个示例是,
// Memory allocation on the stack
void b(char **p) {
char * str="print this string";
*p = str;
}
int main(void) {
char * s;
b(&s);
s[0]='j'; //crash, since the memory for str is allocated on the stack,
//and the call to b has already returned, the memory pointed to by str
//is no longer valid.
return 0;
}
评论中的解释让我想到,字符串文字的内存不是静态的吗?
那里的实际错误不是您不应该修改字符串文字,因为它是未定义的行为吗?或者那里的评论是否正确,而我对该示例的理解是错误的?
进一步搜索后,我看到了这个问题:referencing a char that went out of scope我从那个问题中了解到,以下是有效代码。
#include <malloc.h>
char* a = NULL;
{
char* b = "stackoverflow";
a = b;
}
int main() {
puts(a);
}
还有这个question同意其他 stackoverflow 问题和我的想法,但反对该网站代码的评论。
为了测试它,我尝试了以下方法,
#include <stdio.h>
#include <malloc.h>
void b(char **p)
{
char * str = "print this string";
*p = str;
}
int main(void)
{
char * s;
b(&s);
// s[0]='j'; //crash, since the memory for str is allocated on the stack,
//and the call to b has already returned, the memory pointed to by str is no longer valid.
printf("%s \n", s);
return 0;
}
正如预期的那样,不会出现段错误。
最佳答案
标准说(强调是我的):
6.4.5 String literals
[...] The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. [...]
[...] If the program attempts to modify such an array, the behavior is undefined. [...]
关于c - 我是否误解了这个关于字符串文字范围的例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54257389/