Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

c - crash when free pointer to function

I have the following struct

typedef struct test {
    int                                 action;
    void                                *data;
    void (*function)(int, void*);
} test;

int execute_func(void(*function)(int a, void *d), int action, void *data)
{
    struct test             *todo;

    todo = calloc (1,sizeof(struct test));
    if (todo == NULL)
    {
        return -1;
    }
    todo->action = action;
    todo->data = data;
    todo->function = function;
    todo->function(todo->action, todo->data);
    return 0;
}

After executing the function, i want to free the allocated structure usinf the following:

if(todo != NULL)
{
    if(todo->data != NULL)
    {
        free(todo->data);
    }
    if(todo->function != NULL)
    {
        free(todo->function); //Cause a crash
    }
    free(todo);
}

but i get a crash.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only can free memory that have been allocated with malloc. So, you can't free function. A function pointer stores address from static memory.

if(todo != NULL)
{
    if(todo->data != NULL)
    {
        free(todo->data);
    }
    free(todo);
}

Also, same remark for data: you have to free it only and only if memory pointed by data have been dynamically allocated with malloc.

And to a more generic point of view, only free dynamically allocated memory if you are owner of it.

To answer of one of OP comments, when you use calloc to your structure, you allocate memory for structure only: an int and two pointer. You don't have allocated memory for function nor for memory pointed by data. To avoid memory leak, you just have to free memory from your structure, ie an int and two pointer (and not for pointed memory, because you don't know how they had been allocated)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...