【问题标题】:Why does the C compiler allow me to use strcpy to overwrite string literal?为什么 C 编译器允许我使用 strcpy 覆盖字符串文字?
【发布时间】:2018-09-24 19:50:54
【问题描述】:

为什么下面的代码在 Visual Studio 中工作?

char* str1 = "This is a test string";
strcpy_s(str1, strlen(str1), "replacing content");

我的理解是 str1 只是一个 char* 指向一个字符串文字,而不是一个字符数组。 而在 strcpy_s()(或 strcpy())中,char 字节从 src 复制到 dst 数组。

在上面的代码中,strcpy() 不是试图覆盖字符串文字吗?如果是,那为什么要编译代码?

附加信息

不仅代码正在编译,我还可以看到新字符串被复制。

void stringCopy_demo() {    
    char* str1 = "1234567890"; //len = 10   
    printf("%s \n", str1);
    strcpy_s(str1, strlen(str1), "content");
    printf("%s \n", str1);  
}

输出

1234567890
content

【问题讨论】:

  • 如果代码编译成功,你试过运行吗?
  • 编译并不意味着它“工作”!
  • 假设您的代码确实可以编译,我认为您需要将问题更改为“为什么 C 编译器允许我使用 strcpy 覆盖字符串文字”?
  • 这是未定义的行为。任何事情都可能发生。这包括“似乎可以工作”和“崩溃”,还修改了代码中其他地方使用的字符串文字 "string""test string"
  • @NovaSysEng 谢谢。我已按照您的建议更改了标题。

标签: c c-strings strcpy


【解决方案1】:

C99 字符串字面量是char[],但修改数组是未定义的行为,请参阅What is the type of string literals in C and C++?

许多编译器都有启用非 const 使用警告的选项,例如 gcc 的 -Wwrite-strings

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多