c-将char**传递给void**函数参数时,指针类型警告与指针到指针类型不兼容



我正在尝试实现一个安全释放函数,该函数擦除已分配的内存,释放内存,然后将指向已分配区域的指针设置为NULL,这样指针在释放后就不能重复使用,也不能用同一函数双重释放。为了实现这一点,我使用了一个指针到指针的参数,它允许我覆盖指向分配内存的指针。

问题是GCC抱怨不兼容的指针类型("但它在我的机器上工作"(;我没想到会有这样的警告。我的理解是,任何指针都可以隐式转换为void*,因此我猜指针的地址也可以转换为void**

同时,我将secure_free()重写为宏,这解决了警告,但我想知道编译器为什么抱怨。

文件securefree.c

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#define STRING_BUFFER_LEN 10
/**
* Securely erases a heap-allocated memory section, frees it and sets its
* pointer to NULL to avoid use-after-free and double-free.
*/
static void secure_free(void** p_p_data, size_t length_in_bytes)
{
if (p_p_data == NULL || *p_p_data == NULL)
{ return; }
memset(*p_p_data, 0, length_in_bytes);
free(*p_p_data);
*p_p_data = NULL;
}
int main(void)
{
// Allocate some data
char* my_string = calloc(STRING_BUFFER_LEN, sizeof(char));
if (my_string == NULL) { return 1; }
// Use the allocated space in some way
my_string[0] = 'a';
my_string[1] = 'b';
// Free using the dedicated function
secure_free(&my_string, STRING_BUFFER_LEN);
return 0;
}

使用GCC编译(修订版6,由MSYS2项目构建,10.2.0(:

$ gcc securefree.c -o securefree
securefree.c: In function 'main':
securefree.c:29:17: warning: passing argument 1 of 'secure_free' from incompatible pointer type [-Wincompatible-pointer-types]
29 |     secure_free(&my_string, STRING_BUFFER_LEN);
|                 ^~~~~~~~~~
|                 |
|                 char **
securefree.c:11:32: note: expected 'void **' but argument is of type 'char **'
11 | static void secure_free(void** p_p_data, size_t length_in_bytes)
|                         ~~~~~~~^~~~~~~~

编辑:宏版本看起来像这个

#define secure_free_macro(ptr, len) if ((ptr) != NULL) { 
memset((ptr), 0, (len)); free(ptr); (ptr) = NULL; }

您试图做的事情不能用便携方式完成,因为不同的指针类型可以有不同的表示;要将空指针分配给该值,必须先将指向指针的指针强制转换为指向实际指针变量的有效类型的指示器,这是不可能的。

然而,你可以使用宏,它和任何宏一样好,而且使用起来更简单:

#define secure_free(x) (free(x), (x) = 0)

这在没有&的情况下有效。

C允许将任何指针隐式转换为void*作为显式异常。请注意,voidchar不兼容的类型。因此,void*char*void**char**也不兼容。这就是编译器发出警告的原因。

要绕过此问题,请将函数签名更改为使用void*:

void secure_free(void* ptr, size_t length_in_bytes) {
void **p_p_data = (void**)ptr;
...
}

为了增加参数是指向指针的指针的保护,可以使用宏:

#define secure_free(x,s) ((void)sizeof **(x), secure_free((x), (s)))
  • 表达式**(x)将不会编译is x不是指向指针的指针
  • sizeof阻止**(x)x的评估以避免副作用
  • (void)让编译器对未使用值的抱怨保持沉默
  • 逗号运算符(X,Y),只返回Y的值,是secure_free(...)的返回值
  • 仅当secure_free用作函数时,才能将其扩展为宏。这允许使用secure_free作为指向函数的指针

额外注意。在代码中

memset(*p_p_data, 0, length_in_bytes);
free(*p_p_data);

编译器可能会优化memset()。我建议强制转换为volatile void *,以强制编译器生成清除代码。

编辑

此外,由于memset丢弃了volatile限定符,因此可能已经用循环清除了内容。

最新更新