www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Is PureMalloc actually... pure?

reply Chris Katko <ckatko gmail.com> writes:
Pure implies (*requires) no side effects, right?

UNIX 98 requires that errno be set to ENOMEM upon failure. 
Purity is achieved by saving and restoring the value of errno, 
thus behaving as if it were never changed.
Saving and restoring a global variable is is __not__ the same as no side effects. without a mutex, two threads could easily create a date race. void* pureMalloc()(size_t size) trusted pure nogc nothrow { const errnosave = fakePureErrno; void* ret = fakePureMalloc(size); fakePureErrno = errnosave; return ret; } I mean, on a practical level, malloc almost never fails so this probably hasn't shown up as a bug in 99% of code.
Jan 11 2020
parent Rob Rau <rfr2 mac.com> writes:
On Saturday, 11 January 2020 at 19:05:48 UTC, Chris Katko wrote:
 Pure implies (*requires) no side effects, right?

UNIX 98 requires that errno be set to ENOMEM upon failure. 
Purity is achieved by saving and restoring the value of errno, 
thus behaving as if it were never changed.
Saving and restoring a global variable is is __not__ the same as no side effects. without a mutex, two threads could easily create a date race. void* pureMalloc()(size_t size) trusted pure nogc nothrow { const errnosave = fakePureErrno; void* ret = fakePureMalloc(size); fakePureErrno = errnosave; return ret; } I mean, on a practical level, malloc almost never fails so this probably hasn't shown up as a bug in 99% of code.
To be posix compliant errno must be thread safe. In linux I believe this is done by each thread having its own thread local errno. -Rob
Jan 11 2020