Venkatesh Chauhan
Venkatesh Chauhan

Reputation: 23

Manipulating C function

Is there exist a way to manipulate C function some how
for eg - we know C printf() function return Number of character printed to the console. So is there any way that i can get number of character but not letting printf() function print to console. using same printf() from stdio.h

I know return is the last statement to get executed in a function hence what i am asking may be impossible but i do want to hear from the community i.e is my hypothesis i.e manipulating c function is possible or not?

Upvotes: 1

Views: 93

Answers (1)

Enzo Ferber
Enzo Ferber

Reputation: 3104

If you have access to the source code and you're able to recompile it with your changes, then sure, you can do it. Consider this:

int foo(int a, int b)
{
    int c = 4;
    int d = 8;
    int f = c * a;
    int g = d * b;
    int h = f + g;
    return h;
}

If you want the value stored in f, there are a couple of ways to do it: 1) you peak into the stack with inline assembly (non-portable, non-reliable), 2) you change the code to expose the variable. Notes on "peaking the stack": what if the architecture does not have a stack? What if the values are all on registers? What if the compiler optimized all the function calls to inline calls? What if...?

Because if you look at the function from the outside, all the function is... is this:

int foo(int a, int b);

You can get an integer from it if you pass two integers to it as arguments. That's all you can do with the API. There is no way in C you can get the value of f or g.

In the analogy, f and g are printf's internal state, and you can not access it. Functions are designed to work as perfect black boxes: it gives you an output based on your input, but how it does it doesn't matter.

Upvotes: 0

Related Questions