我正在使用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时,它并不喜欢它。有人能看到我在做什么错吗?

谢谢

最佳答案

我可以轻松找到的有关avcall的唯一信息是2001年的信息,但它确实建议使用POSIX。如果您可以在Linux上运行您的东西, valgrind 就会发现您的内存错误。这是一个了不起的工具。

关于c - 无效的指针和ffcall库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1813807/

10-14 05:42