简体   繁体   中英

unfamiliar function declaration in c

I was looking into SslSplit code . And I faced some unfamiliar, strange function declarations in opts.h file. Definition of those functions are quite straightforward but I could use some help about declarations. Here it is:

opts.h:

char *proxyspec_str(proxyspec_t *) NONNULL(1) MALLOC;
void opts_set_crl(opts_t *, const char *) NONNULL(1,2);

opts.c:

void
opts_set_crl(opts_t *opts, const char *optarg)
{
    if (opts->crlurl)
        free(opts->crlurl);
    opts->crlurl = strdup(optarg);
    log_dbg_printf("CRL: %s\n", opts->crlurl);
}

char *
proxyspec_str(proxyspec_t *spec)
{
    char *s;
    char *lhbuf, *lpbuf;
    char *cbuf = NULL;

    // Some code..

    return s;
}

attrib.h:

#define WUNRES          __attribute__((warn_unused_result))
#define MALLOC          __attribute__((malloc)) WUNRES
#define NONNULL(...)    __attribute__((nonnull(__VA_ARGS__)))

My question is, what are the meanings of NONNULL and MALLOC at the end of the function declarations?

As you pointed out yourself, NONNULL and MALLOC are just macros. Their replacement starts with __attribute__ which is a compiler extension keyword, used to define attributes in a function.

The __VA_ARGS__ is the replacement for the variable number of arguments in a macro (declared with the ... ). So this declaration:

void opts_set_crl(opts_t *, const char *) NONNULL(1,2);

Is transformed by the preprocessor (before the compiler sees it) into:

void opts_set_crl(opts_t *, const char *) __attribute__((nonnull(1,2)));

What this effectively does is preventing the first and second parameters of being NULL . If you check the documentation of a compiler which supports this extension, such as gcc or clang you will find the complete description.

The other attribute, malloc , from the GNU manual :

This tells the compiler that a function is malloc-like, ie, that the pointer P returned by the function cannot alias any other pointer valid when the function returns, and moreover no pointers to valid objects occur in any storage addressed by P.

Using this attribute can improve optimization. Functions like malloc and calloc have this property because they return a pointer to uninitialized or zeroed-out storage. However, functions like realloc do not have this property, as they can return a pointer to storage containing pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM