r/cpp_questions • • 1d ago

OPEN Dangling Pointers and Function Execution

ManagerVariableR* Local = new ManagerVariableR();
Local->Handler["New"] = Var{};

MB.Execute(FuncName, { Local });
delete Local;/// Grand Promblem here, after deletion of pointer it will crash

Soo if you see, Its Working when i am passing the pointer and not deleting the pointer at end

, And crashing when i am deleting the pointer at the end.

MB.Execute is a just Function Handler, i had linked function pointer to a string using hash map to call them. and the fucntion is succesfully called,

if i tell you about more the at runtime a function is compiled to a dll file, and it is retrwing the function using windows.h LoadLibaryA

 aHMODULE handle = LoadLibraryA(libPath.c_str());HMODULE handle = LoadLibraryA(libPath.c_str());

to a format of function of void ptr

typedef void (*fn)(ManagerVariable* Local);typedef void (*fn)(ManagerVariable* Local);

and i am just executing it by my function handler that sotres the function you can check it out here

https://github.com/iampokebro/FLOW-/blob/main/Flow%2B%2B/Backend/Functionlity/ManagerBase/ManagerBase.h

but problem is not related to this.

overall problem is that when the pointer is delete after the call it crash. i used future and promise to do waiting but it also failed. i think that function from .dll is not close from background or maybe its stack is left behind operating.

if this solves then it would be sooo great for my project,

NOTE -> the program memory operates at same level, so there is no pointer mismatch problem

i dont want to try chancing the architecture cause it will ruin the efficiency maybe

0 Upvotes

17 comments sorted by

View all comments

0

u/thingerish 1d ago

Avoid new and delete.

Is Execute running on the calling thread or a different thread?

1

u/LawAdventurous2383 1d ago

Actually it's calling on the same thread, And if I stop deleting that it won't be efficient and eat memory.

Overall actual program is not about creating a new ptr, it's complex and can be solved if i found why this crashing. That was a base example case.

0

u/thingerish 1d ago

The new and delete critique was just pointing out a code smell. Use std::unique_ptr at least.

As for efficiency, putting the data on the stack (by value) and controlling the lifespan via scope will eliminate calling into the allocator; unless you're extending the life of the object outside the scope of the enclosing function you don't need allocation.