var pint: ptr int
pint = cast[ptr int](alloc(sizeof(int)))
pint[] = 10
# print 10
echo (pint[])
# free memory
dealloc(pint)
# no runtime error
dealloc(pint)
# still print 10
echo (pint[])
As per manual, dealloc() frees the memory allocated with alloc, alloc0 or realloc. If one tries to access freed memory (or just freeing it twice!) a core dump may happen.
In that case how does above code work? Even multiple call to dealloc() worked without any any core dump.
Hi Araq, with -d:useSysAssert it throws [SYSASSERT] alloc 2 error at runtime.
I commented the second dealloc() - the expectation was that it will throw runtime error for last line echo (pint[]). But there was no error and it printed the value 10.
Does not dealloc(pint) set pint to nil?
Nope - why should it? dealloc simply deallocates memory - it's assumed that any remaining pointers to that memory won't be used. To set the pint variable to nil, dealloc would need a reference/pointer to the pint variable, (in this case, it's passed by value) which would be inefficient and pointless in most cases.
Most of the manual memory management procedures in Nimrod - dealloc, realloc, etc. - are closely tied to their C counterparts behavior. As far as I know, C's dealloc doesn't set the pointer it's given to 0, it just sets the memory region the pointer represents to 0.
Hi Varriount, thanks for your explanation.
In my opinion after dealloc() the memory should not be accessible, which means any code trying to access it should throw runtime error (including echo (pint)). Is it different in nimrod?
Setting the pointer to nil does not gain you much:
var a = cast[ptr int](alloc(sizeof(int)))
var b = a
dealloc(a)
echo b[] # oops
And setting all pointers that hold this address to nil is much more inefficient than a GC. Nim's manual memory management is not different from C or even Ada in this respect.
Most of the manual memory management procedures in Nimrod - dealloc, realloc, etc. - are closely tied to their C counterparts behavior.
Not that much. realloc in particular doesn't deal with nil or other special cases that Ansi C specifies etc for efficiency reasons.