Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a code in buffer?

Tags:

c

runtime

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?

like image 906
user2943407 Avatar asked Feb 26 '26 02:02

user2943407


1 Answers

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

like image 185
mafso Avatar answered Feb 28 '26 11:02

mafso