当您使用以下标志编译时,下面的代码在 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/