www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.ldc - strange behavior with malloc and free

reply Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= <aferust gmail.com> writes:
Platform: windows
Compiler version: ldc2-1.14.0-windows-x64 or 
ldc2-1.17.0-windows-x64

When I compile and run the following code. values of a[] is still 
accessible after calling free(a) somehow. Using dmd code prints 
some random memory values as expected. Is this a problem with ldc 
or am I lack of some information about ldc?

code:
```
import core.stdc.stdio;
import core.stdc.stdlib;

int main()  nogc nothrow{

     int* a = cast(int*)malloc(2*int.sizeof);
     a[0] = 1;
     a[1] = 2;

     free(a);

     printf("%d - %d \n", a[0], a[1]); // data is still accessible!

     return 0;
}
```
Oct 11 2019
parent reply Jack Applegame <japplegame gmail.com> writes:
Accessing freed memory leads to undefined behavior.
Oct 11 2019
parent reply Ferhat =?UTF-8?B?S3VydHVsbXXFnw==?= <aferust gmail.com> writes:
On Friday, 11 October 2019 at 11:03:32 UTC, Jack Applegame wrote:
 Accessing freed memory leads to undefined behavior.
i agree with you. But, it is interesting for me to face the same exact undefined behavior with ldc even on different computers.
Oct 11 2019
parent Johan <j j.nl> writes:
On Friday, 11 October 2019 at 11:17:04 UTC, Ferhat Kurtulmuş 
wrote:
 On Friday, 11 October 2019 at 11:03:32 UTC, Jack Applegame 
 wrote:
 Accessing freed memory leads to undefined behavior.
i agree with you. But, it is interesting for me to face the same exact undefined behavior with ldc even on different computers.
DMD and LDC may be using different C libs to call printf. printf may allocate, and thus overwrite the memory locations that you freed. Undefined behavior doesn't mean it has to be random. ;) -Johan
Oct 11 2019