malloc error when trying to assign the returned pointer to a struct field

rempas rempas at tutanota.com
Fri Sep 8 13:32:00 UTC 2023


On Friday, 8 September 2023 at 13:05:47 UTC, evilrat wrote:
>
> You run with -unittest compiler flag? Well, that does nothing 
> for me with betterc (without it is ok).
>
> I did stupid and unsafe things like malloc(0) and writing out 
> of bounds but still no crash, it works fine.
>
> I guess it depends on your libc, tested this on ubuntu 23.04 
> with gcc12 install and ldc 1.32.2
>
> ```d
> import core.stdc.stdlib;
> import core.stdc.stdio;
>
> alias u64 = ulong;
> alias i64 = long;
>
> struct Vec(T) {
> private:
>   T* _ptr = null; // The pointer to the data
>   u64 _cap = 0;   // Total amount of elements (not bytes) we 
> can store
>   u64 _len = 0;
>
> public:
>   /* Create a vector by just allocating memory for it. The null 
> terminator is not set for
>      strings as, the vector is considered empty and we should  
> first push something to it
>      in order to use it! */
>   this(i64 size) {
>     this._len = 0;
>     this._cap = size;
>
>     static if (is(T == char)) { size += 1; } // Additional 
> space for the null terminator
>     this._ptr = cast(T*)malloc(size);
>   }
>
>   ref T opIndex(size_t idx) { return _ptr[idx]; }
> }
>
> extern(C)
> void main()
> //unittest
> {
>     enum el = 3;
>     auto vec = Vec!char(10);
>     assert(vec._ptr);
>     vec[el] = 'h';
>     assert(vec[el] == 'h');
>     printf("ptr = %p\n", vec._ptr);
>     printf("vec ptr = %p\n", &vec[el]);
>     printf("vec local = %p\n", &vec);
>     printf("vec[%d] = %c\n", el, vec[el]);
>     foreach (i; 0..vec._cap) {
>       printf("-");
>     }
>     printf("\n");
>     foreach (i; 0..vec._cap) {
>       printf("%d", vec[i]);
>     }
>     printf("\n");
>     printf("run ok\n");
> }
> ```
>
> ldc2 -betterC -run membug.d
>
> output
>
> ```
> ptr = 0x55cb701de2a0
> vec ptr = 0x55cb701de2a3
> vec local = 0x7fffa1542258
> vec[3] = h
> ----------
> 000104000000
> run ok
> ```

As D's "uninttest" feature is disabled on BetterC, I have wrote 
my own testing suit (with is very simple). I just said that to 
point out that I'm testing this data structure (along side other 
things) and I cannot find anything wrong.

I have made a search on the web and I found out one thread that 
pointed out that it may be a Glibc error. However, because like I 
said the problem only happens when I assign the returned value to 
the `_ptr` field, I just wanted to post here in case someone has 
a similar experience and if it's a compiler bug in which case, we 
should report it.

I will use a VM to test my code in another environment and I'll 
be back to report!


More information about the Digitalmars-d-learn mailing list