Re: Function that reproduces itself
Jim Langston wrote:
[..]
The question has already been answered, but I had to try out of
curiosity. This program gives a memory violation trying to write to
memory on the 2nd call to FuncP. I was sure it wouldn't work, but
had to see what would happen anyway.
#include <string>
#include <iostream>
int TestFunction()
{
return 2;
}
typedef int (*Func)();
int main()
{
Func FuncP;
FuncP = TestFunction;
int x = FuncP();
std::cout << x << std::endl;
FuncP = (Func)malloc( 1000 );
So, here 'FuncP' is a pointer to *data*. Even though you cast it to
a pointer to function, it doesn't really point to any function, does it?
memcpy( FuncP, TestFunction, 1000 );
Now, since 'TestFunction' is not a pointer to an object, the behaviour
of that code is undefined. But even if we assume that you're allowed
to read bytes from the memory location behind 'TestFunction', you're
storing those bytes into data memory.
x = 4;
x = FuncP(); // Crashes here
And here you're asking to treat the data as if it were *code*.
In modern OSes, you cannot execute data unless you have special
permissions or changed permissions (or properties) of the memory
where you want to create code. Of course it doesn't work.
free(FuncP);
std::cout << x << std::endl;
std::string wait;
std::cin >> wait;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask