r/C_Programming • u/TessaFractal • May 21 '26
Question Are runtime created functions possible? (Cursed ideas)
This sounds like a bad idea, but I'm curious if it's even possible. But imagine you have a function that needs different parts of it turned on and off depending on user selected parameters. Instead of a bunch of if statements for each part, can you create the resultant function needed at runtime, and just call that, skipping the need for if statements at every call?
I feel like you could do a list of function pointers, and call them all in sequence, and that also sounds cursed, and not a thing I've even heard of.
But wondering if a solution like: copying the machine code for a function into memory, and then casting the pointer as a pointer to function and calling it, is that even possible.
View all comments
Show parent comment
5
u/aioeu May 22 '26 edited May 22 '26
mprotectexists.Not sure what you mean by "retroactively".
mprotectchanges the permissions used for future accesses, not past accesses, of course, so it's anything but "retroactive".Even without
mprotectit is often possible to map the same physical memory twice, at different virtual addresses and with different permissions. But you do have to think about cache coherency once you start doing shenanigans like that.