r/C_Programming • • 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.

73 Upvotes

53 comments sorted by

View all comments

Show parent comment

5

u/aioeu May 22 '26 edited May 22 '26

so there's no easy way to copy code into a memory page that's initially read-write (and not executable) and retroactively mark it read-only + executable

mprotect exists.

Not sure what you mean by "retroactively". mprotect changes the permissions used for future accesses, not past accesses, of course, so it's anything but "retroactive".

Even without mprotect it 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.

3

u/pjl1967 May 22 '26

I completely forgot about mprotect. I stand corrected.