1
 int test_malloc(void **ptr, size_t size)
 {
    (*ptr) = malloc(size);
    return 0;
 }

 int test_app()
 {
   char *data = NULL;
   int ret = 0;
   ret = test_malloc((void **)&data, 100);
 }

编译器:gcc 4.1.2

其中,我正在使用 -O2 和 -Wall ,我认为它们正在打开一些检查这一点的选项。

4

3 回答 3

3

您有一个 type 的变量char*,并且test_malloc您正在通过 type 的左值对其进行修改void *,这违反了严格的别名规则。

你可以这样解决它:

 int test_app()
 {
   char *data = NULL;
   void *void_data = NULL;
   int ret = 0;
   ret = test_malloc(&void_data, 100);
   data = (char*)void_data;
 }

但更好的是让 test_malloc 返回void*以避免此类问题。

于 2012-05-10T06:11:48.407 回答
2

You cannot do what you're trying to do in C; it's invalid code. If you want to use void * to return generic pointers, the only way to do so is the return value. This is because void * converts to any pointer type, and any pointer type converts to void *, but void ** does not convert to a pointer to some other type of pointer, nor do pointers to other pointer types convert to void **.

于 2012-05-10T06:12:05.267 回答
1

我试着像这个一样工作正常

void * test_malloc(int size)
{
    void *mem = malloc(size);
    if (mem == NULL)
    {
        printf("ERROR: test_malloc %d\n", size);
    }
    return mem;
}

 int test_app()
 {
   char *data;
   int ret = 0;
   data = test_malloc(100);

   if(data != NULL)
         free(data);
 }
于 2012-05-10T06:09:38.670 回答