Home > Software engineering >  Does this cause memory leakage by not freeing the function pointer? C
Does this cause memory leakage by not freeing the function pointer? C

Time:10-02

Does this code architecture cause memory leakage by not freeing m_func?

And could this be tempered with if this code would be executed at a closed server? Like finding the address of the pointer and replacing the code of the function pointee with malicious code? If so how could I solve this?

#include <iostream>
template <typename Func>
struct endpoint_t {
    void* m_func;
    endpoint_t(Func&& func) : m_func((void*) func) {}
    auto execute() {
        return ((Func*) m_func)();
    }
};
int hello_world() {
    std::cout << "Hello World! \n";
    return 0;
}
int main() {
    endpoint_t end(hello_world);
    end.execute();
}

Edit: This is the actual goal of the code: To store multiple endpoint functions inside a vector.

#include <vector>
#include <iostream>
template <typename Func>
struct endpoint_t {
    void* m_func;
    endpoint_t(Func&& func) : m_func((void*) func) {}
    auto execute() {
        return ((Func*) m_func)();
    }
};
int hello_world() {
    std::cout << "Hello World! \n";
    return 0;
}
int hello_world2() {
    std::cout << "Hello World 2! \n";
    return 0;
}
int main() {
    std::vector<endpoint_t<???>> array;
    array.push_back(hello_world);
    array.push_back(hello_world2);
}

CodePudding user response:

Assuming the prototypes of all your 'hello world' functions is the same (int return value, no parameter), you don't need templates at all. Just store a function pointer.

typedef int (*Func_t)();
int hello_world() {
    std::cout << "Hello World! \n";
    return 0;
}
int hello_world2() {
    std::cout << "Hello World 2! \n";
    return 0;
}
int main() {
    std::vector<Func_t> array;
    array.push_back(&hello_world);
    array.push_back(&hello_world2);
}

Assuming that the prototypes do differ, it becomes a wee bit more difficult, but not very much so, thanks to std::function.

int hello_world() {
    std::cout << "Hello World! \n";
    return 0;
}
int hello_world2(int value) {
    std::cout << "Hello World 2! \n";
    return 0;
}
int main() {
    std::vector<std::function<int ()>> array;
    array.push_back(&hello_world);
    array.push_back(std::bind(&hello_world2, 2));
}

Please note, that std::bind and lambdas require you to pass any given parameter at the time of binding. You cannot add the parameter later.

  • Related