I was wondering if i could excute code that has been stored in a buffer. For Example :
char buffer[20] = "printf(\"Stackoverflow\");";
Is there way to execute the printf statement?
I was wondering if i could excute code that has been stored in a buffer. For Example :
char buffer[20] = "printf(\"Stackoverflow\");";
Is there way to execute the printf statement?
There is no eval
-like construct in C as there is in some so-called scripting languages. As C is usually compiled to machine code and not interpreted at run-time, implementing such features would require a platform with some C compiler or C interpreter in order to make the program run.
You may take a look at this question: Is there an interpreter for C? and inspect the links there or search for C interpreters.
And as long as the strings you want to be executed are known at compile-time (i.e. you don't create them depending on some input) you can use function pointers:
void print_hello(void) {
puts("Hello, world!");
}
void print_goodbye(void) {
puts("Goodbye.");
}
int main(void) {
void (*printer)(void) = print_hello;
printer();
printer = print_goodbye;
printer();
return 0;
}
where you may set printer
to the address of any function (with a compatible type), so you don't need to know at compile-time which function eventually will be called.
HTH