Skip to content

Commit

Permalink
Ensure memory is freed in C
Browse files Browse the repository at this point in the history
- Deallocate memory
- Ensure to decrement reference counts for "new" references obtained
  to Python objects
  • Loading branch information
rebeccafair committed Jun 2, 2021
1 parent f98605c commit 601a32a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
10 changes: 9 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
`Unreleased <https://github.com/pace-neutrons/Euphonic/compare/v0.3.2...HEAD>`_
`Unreleased <https://github.com/pace-neutrons/Euphonic/compare/v0.3.3...HEAD>`_
----------

`v0.3.3 <https://github.com/pace-neutrons/Euphonic/compare/v0.3.2...v0.3.3>`_
------

- Bug fixes:

- Fixed memory leak when using the C extension and making multiple calls to
``calculate_qpoint_phonon_modes``

`v0.3.2 <https://github.com/pace-neutrons/Euphonic/compare/v0.3.1...v0.3.2>`_
----------

Expand Down
37 changes: 29 additions & 8 deletions c/_euphonic.c
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ static PyObject *calculate_phonons(PyObject *self, PyObject *args) {
return NULL;
}

// Load library functions
// Load before calling PyObject_GetAttrString so we don't have to
// py_DECREF if library loading fails
ZheevdFunc zheevd;
zheevd = get_zheevd(scipy_dir);
if (zheevd == NULL) {
PyErr_Format(PyExc_RuntimeError, "Could not load zheevd function\n");
return NULL;
}

// Get rest of vars from ForceConstants object
if (attr_from_pyobj(py_idata, "crystal", &py_crystal) ||
attr_from_pyobj(py_idata, "_n_sc_images", &py_n_sc_ims) ||
Expand Down Expand Up @@ -172,14 +182,6 @@ static PyObject *calculate_phonons(PyObject *self, PyObject *args) {
n_gvecs = PyArray_DIMS(py_gvec_phases)[0];
}

// Load library functions
ZheevdFunc zheevd;
zheevd = get_zheevd(scipy_dir);
if (zheevd == NULL) {
PyErr_Format(PyExc_RuntimeError, "Could not load zheevd function\n");
return NULL;
}

omp_set_num_threads(n_threads);
#pragma omp parallel
{
Expand Down Expand Up @@ -228,6 +230,25 @@ static PyObject *calculate_phonons(PyObject *self, PyObject *args) {
diagonalise_dyn_mat_zheevd(n_atoms, qpt, dmat, eval, zheevd);
evals_to_freqs(n_atoms, eval);
}
if (dipole) {
free((void*)corr);
}
}

// PyObject_GetAttrString returns a "new" reference, need to decref
Py_DECREF(py_crystal);
Py_DECREF(py_n_sc_ims);
Py_DECREF(py_sc_im_idx);
Py_DECREF(py_cell_ogs);
Py_DECREF(py_atom_r);
if (dipole){
Py_DECREF(py_born);
Py_DECREF(py_dielectric);
Py_DECREF(py_H_ab);
Py_DECREF(py_dipole_cells);
Py_DECREF(py_gvec_phases);
Py_DECREF(py_gvecs_cart);
Py_DECREF(py_dipole_q0);
}

return Py_None;
Expand Down

0 comments on commit 601a32a

Please sign in to comment.