Thread: Is it possible to copy function to a const function pointer by memcpy?

  1. #1
    Registered User
    Join Date
    Mar 2009

    Is it possible to copy function to a const function pointer by memcpy?

    I want to change an CONST function pointer after it's initialed, I tried the following, i printed the pointer address copyed by memcpy, the address is different from the function address. Also, I get a seg fault on executing it. How can i do this?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    void function(void){

    const void (*function_pointer)(void)=NULL;

    int main(){
    memcpy(&function_pointer, &function, sizeof(fuction_pointer));
    fprintf(stderr, "%p, %p\n", &function_pointer, &function);
    return 0;

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    &function_pointer is not the same as the content of function_pointer.

    memcpy() should complain that you are trying to modify a const variable, really, so it should not allow you to do what you want to do. The variable is either const, or it isn't! If you modify it, then it should not be const.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    it is not const pointer - it is pointer to const - should be no problem to modify it

    #include <stdio.h>
    void function(void)
    const void (*function_pointer)(void)=NULL;
    int main()
    	function_pointer = &function;
    	return 0;
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM