user3115031
user3115031

Reputation: 41

function cast leads to gcc abort command

in the following code in file func.c:

#include <stdio.h>

int Myfunc1(int i, int z)
{
    return i;
}

int main()
{
    int ans;

    /*  casting the function into an 'int (int)' function   */
    ans = ((int(*)(int))(Myfunc1))(5);

    printf("ans: %d\n\n", ans);

    return 0;
}

i tried to cast an int(int,int) function into an int(int) function an got the gcc warning and note:

func.c:13:32: warning: function called through a non-compatible type [enabled by default]
func.c:13:32: note: if this code is reached, the program will abort

and when trying to run i get:

Illegal instruction (core dumped)

but if i compile this file with a .cpp ending with the gcc compiler it works OK. can anyone explain the problem of the compiler in the .c case?

Upvotes: 4

Views: 907

Answers (3)

user1508519
user1508519

Reputation:

The problem is your signature for Myfunc1 and the function pointer you try to cast it to are of incompatible types. Instead, you need to do this:

ans = ((int(*)(int, int))(Myfunc1))(5, 5);

The link Thomas Ruiz posted explains why it is undefined behavior.


In summary:

Annex J.2

The behavior is undefined in the following circumstances:

-- A pointer is used to call a function whose type is not compatible with the pointed-to type (6.3.2.3).

6.3.2.3/8

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

Upvotes: 2

karlphillip
karlphillip

Reputation: 93410

#include <stdio.h>

int Myfunc1(int i, int z)
{
    return i;
}

int main()
{
    // define a function pointer and initialize it to NULL
    int (*ans)(int, int) = NULL;

    // get function pointer from function 'Myfunc1'
    ans = Myfunc1(5, 6);

    // call function using the pointer
    printf("ans: %d\n", (*ans));

    return 0;
}

Upvotes: 1

Thomas Ruiz
Thomas Ruiz

Reputation: 3661

GNU GCC recognises all of the following as C++ files, and will use C++ compilation regardless of whether you invoke it through gcc or g++: .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx

From https://stackoverflow.com/a/1546107/1767861

In that case, gcc compiles it in c++, which seems to accept the cast. Why is that ? See https://stackoverflow.com/a/559671/1767861

Upvotes: 2

Related Questions