VS2010 C $ C $Ç - 字符串池 [英] VS2010 C code - String pooling
问题描述
在下面VS 2010 code崩溃,当你用下面的标记编译如果添加/ GF-或删除opimization标志,他们不死机。这次事故发生在装配code这翻译'如果(路径[我] =='/')。我想了解编译器在这里所做的优化,并导致崩溃。期待着一些指点。
-Karthik
cl.exe时/ MD / O2 test.c以
//
TEST.C
的#include<&stdio.h中GT;#包括LT&;&string.h中GT;无效testpath(字符*路径,诠释BUFSIZ)
{ INT I; 的printf(%P \\ N,路径);
对于(i = 0; I< strlen的(路径);我++){
如果(路径[我] =='/'){
路径[我] ='\\\\';
}
}
}诠释的main()
{ 为const char *路径=testexport.prj;
字符* PATH1 =testexport.prj;
的printf(%P \\ N,路径);
的printf(%P \\ N,路径1);
testpath(路径,1024);
}
试图修改字符串的内容
调用未定义行为。
从ISO C99(第6.4.5节/ 6
)
有unspeci网络编辑这些阵列是否提供了不同的元素具有适当的值。 如果该程序试图修改这样的阵列,该行为是理解过程网络斯内德
块引用>从ISO C ++ - 98(
第2.13.4 / 2
)
不管所有的字符串文字是不同的(也就是说,存储在非重叠的对象)是实现定义。 试图修改字符串的效果是不确定的。
块引用>在大多数实现(包括MSVC)这会导致你的应用程序崩溃。
Below code crash in VS 2010 when you compile with following flag and if you add /GF- or remove the opimization flag they don't crash. The crash occur at assembly code which translate 'if( path[i] == '/' )'. I like to understand the optimization that compiler does here and lead to crash. Looking forward for some pointers.
-Karthik
cl.exe /MD /O2 test.c
//
Test.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); }
解决方案Trying to modify the contents of a
string literal
invokes Undefined Behaviour.From ISO C99 (
Section 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
From ISO C++-98 (
Section 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.
On most implementations (including MSVC) this results to crash of your application.
这篇关于VS2010 C $ C $Ç - 字符串池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!