简体   繁体   中英

Doing memcpy without allocating memory with malloc before

I am asking myself why this piece of code works well when I haven't allocated memory for fptr. I would expect that it has rather an Undefined Behavior because of doing memcpy without allocating memory for fptr or?

struct conf *pconf = NULL; 
void (*fptr)(char *, struct conf **);
void *temp = dlsym(dlptr, "config_run_all"); 
memcpy(&fptr, &temp, sizeof fptr); 
fptr("test.conf", &pconf);

You have allocated memory for fptr :

void (*fptr)(char *, struct conf **);`

This declares fptr as a pointer to function.

The memcpy() assigns the value from temp into fptr , making it so that fptr points to the function that temp points to.

What would be problematic would be omitting the & from the memcpy() ; then you'd be trying to copy to memory when fptr has not been set to point to anything.

Your code is basically equivalent to:

struct conf *pconf = NULL; 
void (*fptr)(char *, struct conf **) = (void (*)(char*, struct conf**)) dlsym(dlptr, "config_run_all"); 
fptr("test.conf", &pconf);

witout temp .

The clue is in the memcpy invocation.

memcpy(&fptr, &temp, sizeof fptr); 

You are copying to the address of the pointer, not dereferencing it. This is overwriting the memory of the pointer variable itself, not what it points to (which is nothing).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM