c - 我是否误解了这个关于字符串文字范围的例子?

标签 c string pointers undefined-behavior string-literals

我正在阅读常见的 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

  1. [...] The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. [...]

  2. [...] If the program attempts to modify such an array, the behavior is undefined. [...]

关于c - 我是否误解了这个关于字符串文字范围的例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54257389/

相关文章:

c++ - 0x0040 和管道符号在这里表示什么?

c# - .Net Framework 中的字符串实习 - 有什么好处以及何时使用实习

java - Android:读取文本文件并存储到 ArrayList<String>

c - 将指针数组转换为数组

c - 如何在C中返回一个二维指针?

c - usrsctp数据接收回调参数值变废话

c - 如果已经比较了一个字符,我如何在两个 c_strings 之间进行比较检查?

c++ - 'CloseToolhelp32Snapshot' : identifier not found

java - 在java中读取文本文件并将其转换为字符串

c - 等式 "*x_ptr = &x "中每个变量的伪代码翻译是什么?