2

我遇到了使用夹板的问题。这是类似的代码

#include <stdio.h>
#include <stdlib.h>

static void getMem(/*@null@*/void **out, size_t size)
{

    if(out == NULL)
        return;

    *out = malloc(size);
}

int main(/*@unused@*/int argc, /*@unused@*/char *argv[])
{
    char *str = NULL;

    getMem((void **)&str, 1);
    if(str != NULL)
    {
        *str = 'a';
        (void)putchar(*str);
        free(str);
    }

    return 0;
}

夹板给出这样的警告信息,

main.c: (in function getMem)
main.c:11:2: Function returns with possibly null storage derivable from
                parameter *out
  A possibly null pointer is reachable from a parameter or global variable that
  is not declared using a /*@null@*/ annotation. (Use -nullstate to inhibit
  warning)
   main.c:10:12: Storage *out may become null
main.c:11:2: Function returns storage out reachable from parameter not
                completely defined (**out is undefined)
  Storage derivable from a parameter, return value or global is not defined.
  Use /*@out@*/ to denote passed or returned storage which need not be defined.
  (Use -compdef to inhibit warning)
   main.c:10:12: Storage **out allocated

对于函数 getMem 中的参数,我需要在使用前检查 NULL 指针。然后返回内存地址。注解“/ @out@ /”不能放在第一个参数之前,因为它在函数中使用。而“/ @null@ /”只表示out可以为null,不能为*out。我不知道如何处理它。有人可以给一些建议吗?提前致谢。

4

1 回答 1

2

最终,您无法使用夹板表达您想要表达的内容。给定的原型根本不可能。主要原因是您需要告诉夹板,即*outan/*@out@*/和 an /*@only@*/。除了夹板没有/*@only@*/通过参数返回存储的概念。每当您放入/*@only@*/参数夹板时,假定有问题的函数free()是内存,但您打算在此处分配。你现在基本上有两个选择:

  • 以夹板可以处理的方式更改您的函数原型。特别是避免通过参数返回分配的内存。
  • 放宽对该函数的检查(例如,将其放在一个单独的、未经检查的文件中)并编写一个包装函数,该函数具有一个夹板可以处理的原型。
于 2014-01-27T07:25:13.973 回答