bab*_*u67 3 string portability pointers d
为什么下面的小样本在Linux64下失败但在Windows32下失败?
module test;
import std.string, std.stdio;
void main(string[] args)
{
string a = "abcd=1234";
auto b = &a;
auto Index = indexOf(*b, '=');
if (Index != -1)
*cast (char*) (b.ptr + Index) = '#';
writeln(*b);
readln;
}
Run Code Online (Sandbox Code Playgroud)
要记住的一件事是,这string是一个别名,(immutable char)[]这意味着尝试写入元素是未定义的行为
我认为行为不同的原因之一是在linux64下编译器将字符串数据放入写保护的内存中,这意味着*cast (char*) (b.ptr + Index) = '#';失败(无论是静默还是使用segfault)