malloc error when trying to assign the returned pointer to a struct field
evilrat
evilrat666 at gmail.com
Fri Sep 8 13:05:47 UTC 2023
On Friday, 8 September 2023 at 11:50:52 UTC, rempas wrote:
>
> That's interesting, I wasn't able to find something else! The
> bug happens when I run the testing suit and well... the tests
> before pass so I cannot find anything that goes wrong except
> for the fact that I do not free the memory that is allocated
> (on purpose).
>
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
```
More information about the Digitalmars-d-learn
mailing list