# Memory error (bad\_alloc) with MPS/density matrix

**URL:** <https://itensor.discourse.group/t/memory-error-bad-alloc-with-mps-density-matrix/2499>\
**Category:** ITensor C++ Questions\
**Tags:** cpp, mps\
**Created:** [September 22, 2025, 3:23pm UTC](https://itensor.discourse.group/t/memory-error-bad-alloc-with-mps-density-matrix/2499 "2025-09-22T15:23:25Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![DavideBianchin4](https://yyz2.discourse-cdn.com/free1/user_avatar/itensor.discourse.group/davidebianchin4/32/811_2.png) [@DavideBianchin4](https://itensor.discourse.group/u/DavideBianchin4)\
**Post date:** [September 22, 2025, 3:23pm UTC](https://itensor.discourse.group/t/memory-error-bad-alloc-with-mps-density-matrix/2499/1 "2025-09-22T15:23:25Z")

</div>

Hello all,

I’m working on a Guassian Boson Sampling setup from scratch, where I apply beam splitter 2-mode gates to an MPS state, and calculate the density matrix at the end to make local measurements. I am following [this page](https://www.itensor.org/docs.cgi?vers=cppv3&page=formulas/mps_two_rdm) from the official documentation for the details.

Below is the code in question:

```cpp
    MPS psi = mps; // Make a local copy
    psi.position(site); // Set the ortho center
    auto psidag = dag(psi); // Create psi bra
    println(psi, psidag);

    psidag.prime("Link"); // Prime bra link indices to contract between them

    // ... Create the reduced density matrix ...
    auto rho = psi(1) * prime(psidag(1), "Site"); // Initialize the tensor
    for (int j = 2; j <= len; j++) { // Contract physical sites priming the site index
        rho *= psi(j);
        rho *= prime(psidag(j), "Site");
    }

```

When the number of physical sites (`len` in the code) is 2, everything works fine. However, as soon as I increase it just to 3, I get the following error:

```bash
terminate called after throwing an instance of 'std::bad_alloc'
  what(): std::bad_alloc
Aborted (core dumped)

```

I managed to pinpoint the faulty lines to the two inside the `for` cycle, but I don’t understand the reason and cannot find a workaround. The local dimension for each site is 9, and the typical bond dimension is around 5, so it should definitely be manageable.

Thank you very much in advance
