On Friday, 8 September 2023 at 13:32:00 UTC, rempas wrote:
On Friday, 8 September 2023 at 13:05:47 UTC, evilrat wrote:
```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
```

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.

Did you run this example program above? Does it crash?
  • malloc error whe... rempas via Digitalmars-d-learn
    • Re: malloc ... evilrat via Digitalmars-d-learn
      • Re: mal... rempas via Digitalmars-d-learn
        • Re:... evilrat via Digitalmars-d-learn
          • ... rempas via Digitalmars-d-learn
            • ... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
              • ... rempas via Digitalmars-d-learn
                • ... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
                • ... rempas via Digitalmars-d-learn
              • ... ryuukk_ via Digitalmars-d-learn
            • ... Kagamin via Digitalmars-d-learn
              • ... rempas via Digitalmars-d-learn
    • Re: malloc ... Hipreme via Digitalmars-d-learn
    • Re: malloc ... bachmeier via Digitalmars-d-learn
    • Re: malloc ... rempas via Digitalmars-d-learn
    • Re: malloc ... Basile B. via Digitalmars-d-learn
      • Re: mal... rempas via Digitalmars-d-learn
        • Re:... H. S. Teoh via Digitalmars-d-learn
        • Re:... Basile B. via Digitalmars-d-learn
          • ... rempas via Digitalmars-d-learn

Reply via email to