c++ - VS2010 C代码——字符串池

标签 c++ c visual-studio visual-studio-2010 winapi

当您使用以下标志编译时,下面的代码在 VS 2010 中崩溃,如果您添加/GF- 或删除优化标志,它们不会崩溃。崩溃发生在翻译 'if( path[i] == '/' )' 的汇编代码处。我喜欢了解编译器在这里所​​做的优化并导致崩溃。期待一些指点。

-卡尔提克

cl.exe/MD/O2 test.c

// 测试.c

#include <stdio.h>

#include  <string.h>

void testpath(char* path, int bufsiz)  
{  

    int i;  

    printf("%p\n", path);  
    for( i=0; i < strlen(path); i++ ) {  
      if( path[i] == '/' ) {  
         path[i] = '\\';  
     }  
  }  
}

int main()  
{  

    const char* path = "testexport.prj";  
    char *path1 = "testexport.prj";  
    printf("%p\n", path);  
    printf("%p\n", path1);  
    testpath(path, 1024);  
}  

最佳答案

尝试修改字符串文字的内容会调用未定义的行为。

来自 ISO C99(第 6.4.5/6 节)

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined

来自 ISO C++-98(2.13.4/2 节)

Whether all string literals are distinct(that is, are stored in non overlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.

在大多数实现(包括 MSVC)上,这会导致您的应用程序崩溃。

关于c++ - VS2010 C代码——字符串池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3287135/

相关文章:

c# - 将项目添加到列表 <> c#

c++ - Linux C++ 库包含不同的 GCC 编译版本

C++ 在带有右值缓冲区的 ostream 中使用 snprintf,格式是否正确?

c++ - 这个插值搜索实现有什么问题?

消费者生产者与 pthreads 有竞争条件

c - 错误: extern declaration of 'i' follows declaration with no linkage

c++ - C++ 中共享库主头文件的最佳实践是什么?

c++ - 反转行的程序不打印到标准输出

visual-studio - 是否有类似 GhostDoc 的 CodeRush 或 ReSharper 插件?

c++ - vfptr/vftable 在类析构函数调用父析构函数时更改基类型