vik santata
vik santata

Reputation: 3109

Why my C++ program crash when convert lambda to function pointer

I tried to convert a lambda function into a function pointer, compile OK, but runtime crash(VC2013). This lambda function is simply to delete a pointer, like this:

typedef void(*pf)(void*);
struct M
{
    ~M(){ printf("dtor\n"); }
};
int main(void)
{
    M *p = new M;
    auto f = [](M*p){delete p; };
    pf p1 = (pf)&f;
    (*p1)(p);
    return 0;
}

[/code]

The crash seems to happen within CRT, unable to debug by myself. Where my crash come from? Thanks a lot

Upvotes: 0

Views: 557

Answers (2)

Jellybaby
Jellybaby

Reputation: 996

Deleting objects through void* is going to get you into trouble.

  1. Change the type of argument to f to be void f(M*)
  2. Don't write code like this it will get you in the end

Here's your code that works on gcc 4.8

#include <cstdio>

class M; //forward dec
typedef void(*pf)(M*);

struct M
{
    ~M(){ printf("dtor\n"); }
};



int main(void)
{
    M *p = new M;
    auto f = [](M*p){delete p; };
    pf p1 = f;
    (*p1)(p);
    return 0;
}

Upvotes: 0

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

There are several problems:

  1. Non-capturing lambdas can be converted to function pointers, pointers to lambdas cannot. Get rid of address-of operator.
  2. Type of function lambda represents is void(*)(M*). pf is void(*)(void*). They are not compatible! Either make lambda take void* or change fp to take M* argument.
  3. C-casts silently do the wrong thing. You do not need one if everything else is correct, implicit conversion is enough.

Following code will work:

#include <cstdio>

struct M
{
    ~M(){ printf("dtor\n"); }
};

typedef void(*pf)(M*);

int main(void)
{
    M *p = new M;
    auto f = [](M*p){delete p; };
    pf p1 = f;
    (*p1)(p);
    return 0;
}

Upvotes: 3

Related Questions