【发布时间】:2021-01-29 14:43:23
【问题描述】:
如何在 C++ 中分配和解除分配函数指针数组?我尝试了两种不同的策略,第一种使用单指针,第二种使用双指针,但我似乎无法让 valgrind 满意。这是我的情况:
// function pointer
typedef double(*function_ptr)(double);
// function that adhers to the interface set by function_ptr
double do_nothing(double x) {
return x;
}
// dynamically create array of @param size function pointers, all pointing to do_nothing
function_ptr **make_function_ptr(int size) {
function_ptr xp = &do_nothing_transform;
function_ptr* xpp = &xp;
auto **trsfm = (ESfcnTrsfm **) malloc(sizeof(function_ptr *));
for (int i = 0; i < size; i++) {
trsfm[i] = (ESfcnTrsfm*) malloc(sizeof(function_ptr));
trsfm[i] = xpp; // same as trsfm[i] = ...
}
return trsfm;
}
// free the array of function pointers
void free_function_ptr(function_ptr **fun, int size) {
for (int i=0; i<size; i++){
free(fun[i]);
fun[i] = nullptr;
}
free(fun);
fun = nullptr;
}
【问题讨论】:
-
你有两个连续分配给
trsfm[i]。第二个擦除由malloc返回的地址。这可能是 valgrind 所抱怨的,但我们不知道,因为您没有向我们展示 valgrind 消息。您也没有提供我们可以自己编译或通过 valgrind 运行的代码:此代码使用do_nothing_transform和ESfcnTrsfm但没有声明它们。此外,您对auto和nullptr的使用看起来像C++,但您标记了问题C。编辑问题以提供minimal reproducible example。 -
@AdrianMole 问题文本中特别提到了C,而原来的标签是C,所以我恢复了编辑。我能看到的 C++ 的唯一指示可能是
auto,但这在 C 中具有不同的含义。我认为用法不正确,但意图是使用 C。 -
@FrançoisAndrieux 可能 - 我不会和你打“编辑战”。但是
nullptr的使用和malloc的显式转换也暗示了C++。 -
啊,是的。我正在使用 C++ 编译器(并遵循 auto 和 nullptr 的编译器提示),但我正在编辑它的 C 代码。
-
@AdrianMole 你说得对,代码包含的 C++ 元素比我注意到的要多,但问题中 "in C" 的存在清楚地表明了意图。
标签: c++ memory-management function-pointers