DanielF
DanielF

Reputation: 161

Issue with function pointer

I'm having a problem with a function pointer that is using the wrong arguments.

The portion of the code which is giving me trouble is this

654     for (k = 0; k < o->nk; k++) {
655       val[0] = o->f(o->xyz+3*k, o->constant, o->f_cent, o->f_sig, val+1);
          ...
659     }

The goal is to call a series of functions (whose pointers are stored in o->f), each of which is called o->nk times in this loop.

The type of o->f is

typedef double (*FLDfunc_t)(double x[], double A, double *ct, double *sig, double grd[]);

All functions run correctly, except for the last one (multsinfunc). Output from gdb is:

#0  0x000000000048712f in multsinfunc (xyz=0x3923c55, A_in=6.28318530717958, cent_in=0x3568ad7, sig_in=0x3568b6e, grad=0x3243f6a879aff)
at MODELS/fields/functions.c:176
#1  0x00000000004863c2 in do_field_operation (o=0x7fffffffdde0, mdl=0x7ffff7e11010, l=CELL_C, kvar=4, kfrom=0, kto=8)
at MODELS/fields/fields.c:655

However, when I go into "do_field_operation", the values for the parameters are different:

gdb$ p o->xyz+3*k
$13 = (double *) 0x918150

gdb$ p o->constant
$14 = 1

gdb$ p o->f_cent
$15 = (double *) 0x880130

gdb$ p o->f_sig
$16 = (double *) 0x880148

The result is that I get a segmentation fault when I try to access "xyz" in multsinfunc. Maybe this is obvious, but I have no idea why this happens. Everything seems to be declared properly. What could be causing this?

Upvotes: 0

Views: 133

Answers (1)

Casey
Casey

Reputation: 42554

You are passing 5 arguments through your call of o->f, but - looking at the gdb output - do_field_operation has 6 parameters. Calling a function through a function pointer of incorrect type invokes undefined behavior.

Upvotes: 1

Related Questions