tam*_*amb 5 c pointers void memory-corruption
我正在使用ffcall(特别是ffcall的avcall包)库来动态地将参数推送到可变参数函数.即我们有
int blah (char *a, int b, double c, ...);
Run Code Online (Sandbox Code Playgroud)
我们希望用来自用户的值来调用此函数.为此,我们创建了该函数的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);
}
Run Code Online (Sandbox Code Playgroud)
现在,我使用avcall的功能是:
int read_row (struct some_struct *a, struct another_struct *b[], ...);
Run Code Online (Sandbox Code Playgroud)
它是这样使用的:
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);
}
Run Code Online (Sandbox Code Playgroud)
但我想使用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");
}
Run Code Online (Sandbox Code Playgroud)
而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);
}
Run Code Online (Sandbox Code Playgroud)
我一直在经历一堆内存损坏错误,似乎它不喜欢我在这里做的事情.我不能发现我这样做的方式有什么问题,是吗?目前,当我尝试释放av_read_rowwhile循环中的malloc时,它不喜欢它.任何人都可以看到我做错了什么吗?
谢谢
我没有详细介绍代码,但可以说以下内容