954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Assign content to a function pointer

Goal: I would like to assign the content of a known function to a function pointer in LINUX environment.
Problem: Get segmentation fault when running the function pointer after assignment.

Procedure:
1). declare a funtion pointer.
2). Allocate memory space to the function pointer using the function' malloc'
3). Copy the content of a known function to the function pointer using
'memcpy'. (the interface of the known function is the same as the function pointer).
4). check the memory content of the function pointer using 'memcmp'.
Result: two memory contents match.
5). Run the function pointer
Result: segmentation fault.

Thanks for your attention.

Richard Wong
Newbie Poster
2 posts since Jul 2004
Reputation Points: 10
Solved Threads: 0
 
Goal: I would like to assign the content of a known function to a function pointer in LINUX environment. Problem: Get segmentation fault when running the function pointer after assignment. Procedure: 1). declare a funtion pointer. 2). Allocate memory space to the function pointer using the function' malloc' 3). Copy the content of a known function to the function pointer using 'memcpy'. (the interface of the known function is the same as the function pointer). 4). check the memory content of the function pointer using 'memcmp'. Result: two memory contents match. 5). Run the function pointer Result: segmentation fault.

Why not just this:Declare function pointer.
Point to the function (assign the pointer).
Run the function pointer.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

Right, the problem with allocating ram and MOVING code into the ram is that jumps and other address references 'fixed up' by the linker are no longer correct.

Here's what Dave was saying:

typedef int (*MyFunctionPtr)(int foo);

int SomeFunction( int foo )
{
return foo;
}

MyFunctionPtr f;

f = SomeFunction; // points to the function SomeFunction()

printf("%d\n",f(4)); // prints '4'

Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You