0

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?

1
  • Maybe xyz+3*(o->nk-1) is out of bound. But it's only a guess Commented Jun 14, 2013 at 19:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

But do_field_operation is the one who calls o->f. I think I figured it out. -> and () have the same precedence. Adding some parenthesis around (o->f) seems to fix the problem, though my K&R book says they associate "left to right", so o->f should evaluate first anyway. That also doesn't explain why there were no errors with the other function pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.