is calling a function pointer to generated code undefined behavior?

As I understand your question, you ask about code such as:

char buffer[200] = "some valid operations";
void (*func)() = reinterpret_cast<void(*)()>(buffer);
func();

I see in the standard in C++ expr.call 7.6.1.3 Function call:

  1. A function call is a postfix expression followed by parentheses containing a possibly empty, comma-separated list of initializer-clauses which constitute the arguments to the function.
    […]
    The postfix expression shall have function type or function pointer type. For a call to a non-member function or to a static member function, the postfix expression shall either be an lvalue that refers to a function […], or have function pointer type.

The func in the above code is an lvalue that refers to a char array and not to a function. The following points in the standard describe other cases of function call expression, such as virtual function call or call to a destructor of some object. These points also do not apply here. To summarize, the standard does not define what will happen when the function call expression is applied to a lvalue that refers to a object that is a char array. Because it’s not defined, hence it’s undefined behavior.

is there a standards-compliant way to create a function pointer to this

Just cast it, via reinterpret_cast. The resulting value is implementation-defined.

and call said function pointer without hitting undefined behavior?

No.

Is calling a function pointer to generated code undefined behavior?

Yes.

Is there a way, in purely standard C++, to somehow call a function generated within a buffer?

No.

But is it undefined behavior or merely implementation-defined what will occur if I attempt to call this function pointer?

Undefined behavior.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top