SIGSEGV (Segmentation Fault) upon setting character in char array (object member var)

Adam D Ruppe destructionator at gmail.com
Tue Dec 19 13:35:47 UTC 2023


On Tuesday, 19 December 2023 at 13:10:40 UTC, John Kiro wrote:
>      class Test {
>        static enum MAX = 10;
>        uint index = 0;
>        auto intArray = new int[MAX];
>        auto charArray = new char[MAX];

This is run at compile time, and the compiler treats any char 
array at compile time as an immutable string literal when it 
crosses the barrier into run time. Moreover, this would be a 
static instance of the initial array; the default reference is 
shared across all objects created (so if you modify intArray then 
`new` another object, you'll see the modified intArray!).

You almost never want to assign arrays or objects at compile time 
like this in a class definition; use constructors instead.

I think the `new char[]` thing being immutable in runtime is a 
compiler bug, it makes it immutable but it is still typed as 
mutable in the type system. but this whole static init thing is 
probably not what you want anyway.


More information about the Digitalmars-d-learn mailing list