Thread overview
strange behavior with malloc and free
Oct 11, 2019
Ferhat Kurtulmuş
Oct 11, 2019
Jack Applegame
Oct 11, 2019
Ferhat Kurtulmuş
Oct 11, 2019
Johan
October 11, 2019
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;
}
```
October 11, 2019
Accessing freed memory leads to undefined behavior.
October 11, 2019
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.
October 11, 2019
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