top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Function cast leads to gcc abort command?

+1 vote
445 views

in the following code func.c :

 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: %dnn", 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.

posted Dec 18, 2013 by Kumar Mitrasen

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

1) When the file has a .cpp extension the C++ compiler is used, which has different diagnostics.
2) Your program has undefined behaviour in both cases, so any behaviour is allowed, including (but not limited to) aborting or executing without error.

answer Dec 18, 2013 by Mandeep Sehgal
Similar Questions
+5 votes

Even I have similar problem:

int (*pfun)(void);
int *pInt = 0;
void fun1()
{
    int i = 5; /* Local to fun1*/

    printf("Outer function");
    pInt = &i; /* As I know address of local variable is valid till function execution */

    int fun2()
    {
      printf("innerfunction");
      printf("%d", *pInt);
    }
    /* fun2 address assign to pfun so that It can be called even after completion of fun1 */
    pfun = fun2;
}

int main()
{
    fun1();
    pfun();
    return 0;
}

Can someone please explain ? I am getting *pInt value 5.

+5 votes

I have a C code like this:

int foo(void)
{ 
 int phase;
 . . .
 phase = 1;
 phase = 2;
 phase = 3;
 . . .
}

In case of -O0 gcc generates machine instructions for every assignment 'phase = ...'. But in case of -O2 gcc does not generate instructions for some assignments. Of course, this is correct. However, is there any way to tell gcc that 'phase' object is inspected by another thread, so it should not remove such statements?

+2 votes

Please share a sample program with detail code.

+4 votes

"Given an array of strings, find the string which is made up of maximum number of other strings contained in the same array. e.g. “rat”, ”cat”, “abc”, “xyz”, “abcxyz”, “ratcatabc”, “xyzcatratabc” Answer: “xyzcatratabc”

...