Thread overview | |||||
---|---|---|---|---|---|
|
September 08, 2018 @safe pointer value modification | ||||
---|---|---|---|---|
| ||||
Hi, According to the docs: https://dlang.org/spec/memory-safe-d.html > Memory-safe code cannot use certain language features, such as: > > Casts that break the type system. > Modification of pointer values. > Taking the address of a local variable or function parameter. So, modification of pointer values is prohibited (if I understand this sentence correctly). However, this code compiles (and will cause a segfault of course): https://run.dlang.io/is/HrUKMy import std.stdio; @safe void main() { int *a; *a = 10; writeln(a); } I'm still learning D so very likely misunderstood something, but isn't that a bug? Thanks! |
September 08, 2018 Re: @safe pointer value modification | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jacob Shtokolov | On Saturday, 8 September 2018 at 17:01:33 UTC, Jacob Shtokolov wrote:
> So, modification of pointer values is prohibited (if I understand this sentence correctly).
@safe code can't manipulate the pointer itself, in order to avoid memory corruption.
So this is forbidden:
void main() @safe
{
int* p = malloc(512);
p++;
}
But in @safe code, the compiler assumes that all pointers you receive are valid. And the null pointer is also valid -- dereferencing it results in a segmentation fault rather than memory corruption.
|
September 11, 2018 Re: @safe pointer value modification | ||||
---|---|---|---|---|
| ||||
Posted in reply to Neia Neutuladh | On Saturday, September 8, 2018 11:06:20 AM MDT Neia Neutuladh via Digitalmars-d wrote:
> On Saturday, 8 September 2018 at 17:01:33 UTC, Jacob Shtokolov
>
> wrote:
> > So, modification of pointer values is prohibited (if I
> > understand this sentence correctly).
>
> @safe code can't manipulate the pointer itself, in order to avoid memory corruption.
>
> So this is forbidden:
>
> void main() @safe
> {
> int* p = malloc(512);
> p++;
> }
>
> But in @safe code, the compiler assumes that all pointers you receive are valid. And the null pointer is also valid -- dereferencing it results in a segmentation fault rather than memory corruption.
Also, mutating the data that a pointer points to is not mutating the pointer. So,
*foo = 42;
is not mutating a pointer, whereas
++foo;
would be. So, the first is allowed in @safe code, whereas the second is not.
BTW, if you have questions about D, please ask them in D.Learn. This newsgroup / mailing list / forum is intended for general discussion on D, not for answering questions about how the language works.
- Jonathan M Davis
|
Copyright © 1999-2021 by the D Language Foundation