Is it safe to read to memory after it has been allocated with `pureMalloc` and `pureRealloc`?
Salih Dincer
salihdb at hotmail.com
Mon Apr 4 09:47:50 UTC 2022
On Monday, 4 April 2022 at 07:48:40 UTC, rempas wrote:
>
> Maybe, I didn't explained it properly. The example works.
> However, I wonder if it randomly works or if it is safe to do
> something like that as if the bytes have been initialized to
> '\0'.
```d
import core.memory : pureMalloc;
import core.stdc.stdio : printf;
//extern (C)
void main()
{
int limit = 23;
auto str = cast(char*)pureMalloc(limit);
//while (limit--) str[limit] = '\0';
// You need this initialize ---^
str[0] = 'J';
str[1] = 'o';
str[2] = 'h';
str[3] = 'n';
printf("My name is: %s\n", str);
// Wrong Output: "My name is: John�U"
}
```
I found no problems when using ```extern()```. But it doesn't
inspire confidence. There is obviously a memory conflict when it
removes ```while()``` loop and does not use ```ekstern()```.
SDB at 79
More information about the Digitalmars-d-learn
mailing list