Core is reset when a function pointer is assigned to a funtion of the same name in another file

I just outline my problem like this, three files: ah, ac, bc, and the code looks like this:

ac

#include "a.h"
#include <stdio.h>

int (*call2)();

int call1(int (*cb)()){
    call2=cb;
    printf("success!");
    return 1;
}

      

hijri

int call1();

      

bc

#include <stdio.h>
#include "a.h"

int call2(){return 0;};

int main(){
    call1(call2);
}

      

then compiling these files with gcc a.c b.c -o b

will result in some changes:

/usr/bin/ld: Warning: alignment 1 of symbol `call2' in /tmp/cc0wbcYh.o is smaller than 8 in /tmp/ccuDjeEs.o
/usr/bin/ld: Warning: size of symbol `call2' changed from 8 in /tmp/ccuDjeEs.o to 11 in /tmp/cc0wbcYh.o
/usr/bin/ld: Warning: type of symbol `call2' changed from 1 to 2 in /tmp/cc0wbcYh.o

      

then start it with. / b ', we get

Segmentation fault (core dumped)

      

My ideas: Apparently the string call2=cb;

caused this corruption. This means that assigning a function to a function pointer of the same name is not a valid operation. I believe the reason has to do with the way the gcc compiler stores the function and function pointer. But I am not familiar with gcc compiler implementation. Can anyone help me?

+3


source to share


1 answer


By defining and call2

as two different objects, with two different types, you violated the rule of one definition. The behavior is undefined.



To achieve the desired behavior, declare both call2

static

so they are connected internally and not conflict with each other.

+3


source







All Articles