私は ffcall (具体的には ffcall の avcall パッケージ) ライブラリを使用して、可変引数関数にパラメーターを動的にプッシュしています。つまり、私たちは持っています
int blah (char *a, int b, double c, ...);
ユーザーから取得した値を使用してこの関数を呼び出します。これを行うには、関数の avcall バージョンを作成します。
int av_blah (char *a, int b, double c, char **values, int num_of_values)
{
av_alist alist;
int i, ret;
av_start_int (alist, &blah, &ret); //let it know which function
av_ptr (alist, char*, a); // push values onto stack starting from left
av_int (alist, b);
av_double (alist, c);
for (i=0;i<num_of_values;i++)
{
// do what you want with values and add to stack
}
av_call (alist); //call blah()
return (ret);
}
今、私が avcall を使用している関数は次のとおりです。
int read_row (struct some_struct *a, struct another_struct *b[], ...);
そして、それは次のように使用されます:
struct some_struct a;
struct another_struct **b = fill_with_stuff ();
char name[64];
int num;
while (read_row (&a, b, name, &num)==0)
{
printf ("name=%s, num=%d\n", name, num);
}
しかし、avcall を使用してこの関数から一定量の値を取得したいのですが、この情報を事前に知りません。したがって、void ポインターの配列を作成し、タイプに応じてスペースを malloc するだけだと考えました。
char printf_string[64]=""; //need to build printf string inside av_read_row()
void **vals = Calloc (n+1, sizeof (void*)); //wrapper
while (av_read_row (&a, b, vals, n, printf_string) == 0)
{
// vals should now hold the values i want
av_printf (printf_string, vals, n); //get nonsense output from this
// free the mallocs which each vals[i] is pointing to
void **ptrs = vals;
while (*ptrs) {
free (*ptrs); //seg faults on first free() ?
*ptrs=NULL;
ptrs++;
}
//reset printf_string
printf_string[0]='\0';
printf ("\n");
}
そしてav_read_row
、次のとおりです。
int av_read_row (struct some_struct *a, struct another_struct *b[], void **vals, int num_of_args, char *printf_string)
{
int i, ret;
av_alist alist;
av_start_int (alist, &read_row, &ret);
av_ptr (alist, struct some_struct *, a);
av_ptr (alist, struct another_struct **, b);
for (i=0;i<num_of_args;i++)
{
switch (type) //for simplicity
{
case INT: {
vals[i] = Malloc (sizeof (int));
av_ptr (alist, int*, vals[i]);
strcat (printf_string, "%d, ");
break;
}
case FLOAT: {
//Same thing
}
//etc
}
}
av_call (alist);
return (ret);
}
大量のメモリ破損エラーが発生しており、ここで行っていることが気に入らないようです。私がこれをした方法に何か問題があることを見つけることができませんか?現時点では、av_read_row
while ループ内で malloc を解放しようとすると気に入りません。もしあれば、誰かが私が間違っていることを見ることができますか?
ありがとう