Skip to content

Commit 51cb39d

Browse files
committed
add assertion to avoid memory access ub
1 parent 5d7624c commit 51cb39d

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

source/module_hamilt_general/module_xc/xc_functional_libxc.cpp

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include <regex>
1515
#include <map>
1616
#include <algorithm>
17+
#include <cassert>
1718

1819
bool not_supported_xc_with_laplacian(const std::string& xc_func_in)
1920
{
@@ -200,17 +201,29 @@ XC_Functional_Libxc::init_func(const std::vector<int> &func_id,
200201
funcs.push_back({}); // create placeholder
201202
xc_func_init(&funcs.back(), id, xc_polarized); // instantiate the XC term
202203

203-
// search for extended parameters, external overwrites in-built if
204-
// the same functional id is found in both maps
204+
// search for extended parameters
205205
const std::vector<double> in_built_ext_params = in_built_xc_func_ext_params(id);
206206
const std::vector<double> external_ext_params = external_xc_func_ext_params(id);
207-
207+
// for temporary use, I name their size as n1 and n2
208+
const int n1 = in_built_ext_params.size();
209+
const int n2 = external_ext_params.size();
210+
211+
// #ifdef __DEBUG // will the following assertion cause performance issue?
212+
// assert the number of parameters should be either zero or the value from
213+
// libxc function xc_func_info_get_n_ext_params, this is to avoid the undefined
214+
// behavior of illegal memory access
215+
const xc_func_info_type* info = xc_func_get_info(&funcs.back());
216+
const int nref = xc_func_info_get_n_ext_params(info);
217+
assert ((n1 == 0) || (n1 == nref) || (n2 == 0) || (n2 == nref));
218+
// #endif
219+
220+
// external overwrites in-built if the same functional id is found in both maps
208221
const double* xc_func_ext_params =
209-
(!external_ext_params.empty()) ? external_ext_params.data() :
210-
(!in_built_ext_params.empty()) ? in_built_ext_params.data() :
222+
(n2 > 0) ? external_ext_params.data() :
223+
(n1 > 0) ? in_built_ext_params.data() :
211224
nullptr; // nullptr if no extended parameters are found
212225

213-
// if there are no extended parameters, do nothing
226+
// if there are no extended parameters, do nothing, otherwise we set
214227
if(xc_func_ext_params != nullptr)
215228
{
216229
// set the extended parameters

0 commit comments

Comments
 (0)