【发布时间】:2012-04-28 08:04:13
【问题描述】:
在 api.h
typedef void* hidden_my_type;
void do_something(my_type x);
在 core.c 中
struct _my_type
{
int a;
}
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x; /*Don't understand is that correct way to do, as I'm getting segmentation fault error */
printf("Value: %d\n", x->a);
}
我认为的其他方式,
struct *_my_type x = (struct _my_type *)malloc(sizeof(struct _my_type));
void_x = x
printf(Value: %d\n", x->a);
但我仍然收到 seg-fault 错误。
好的,这里是 void*.... 的问题。
例如 在 core.c 中
void init_my_type(hidden_my_type a)
{
my_type *the_a = malloc(...);
a = the_a // <<<<<<<<<<<<<<<<<<<<<<<<<<<< is this correct?! a is void* and the_a // is original type
pthread_cond_init(&the_a->...);
.. (in short any other methods for init ..)
}
void my_type_destroy(my_hidden_type x)
{
my_type *the_x = x;
pthread_detroy(&the_x-> ...);
}
在 main.c 中
test()
{
my_hidden_type x;
init_my_type(x);
....
my_type_detroy(x);
}
它自己应该失败。在 main.c 测试函数中,x 是 void* ... init 将分配,但在销毁时我再次传递 void* .. 可以是任何东西!
编辑(为我解决)
在 api.h
typedef void* hidden_my_type;
void do_something(my_type x);
在 core.c 中
struct _my_type
{
int a;
}
void init_hidden_type(hidden_my_type void_p_my_type)
{
struct _my_type *real_my_type = (struct _my_type *)malloc(sizeof(struct _my_type));
//--- Do init for your type ---
void_p_my_type = real_my_type;
}
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x;
printf("Value: %d\n", x->a);
}
【问题讨论】:
-
请出示您的实际代码,而不是重新编写的代码(我可以说这不是您的真实代码,因为它不可能编译)。
-
另外,不要在 typedef 中隐藏指针;很混乱!
-
好吧,我的实际代码与此类似..我无法上传!!!并且出于不透明类型的原因,我正在使用 void* ...它令人困惑但需要这样做! :(
-
您应该创建一个 10 行测试用例,有人可以将其粘贴到编辑器中,编译、运行并查看您描述的问题。
-
char *x = malloc(16); memset(x, '\0', 32); char *y = malloc(256);是陷入麻烦的一种似是而非的方式(不保证,但似是而非)。另一个是:char *x = malloc(16); free(x); memset(x, '\0', 16); char *y = malloc(256);。在这两个示例中,您通过写入未分配给您的内存来滥用内存。当你这样做时,malloc()很容易让你崩溃。
标签: c casting void-pointers