简体   繁体   中英

C: Passing a function without arguments to pthread_create

I'm curious if the following code has a well-defined behavior:

#include <pthread.h>
#include <stdio.h>

void *f()
{
    printf("hey\n");
    return NULL;
}

int main()
{
    pthread_t th;
    if (pthread_create(&th, NULL, f, NULL) == 0) {
        pthread_join(th, NULL);
    }
}

gcc does not produce any warning if I compile it with -Wall -Wextra (see here: https://godbolt.org/z/fEvGesqad ). However, I'm wondering why I can pass f as a parameter to pthread_create , because a function with the signature void xxx(void *) is expected.

Is it safe to do this, or will it lead to undefined behavior?

Thanks

I believe this is a bug in both gcc and clang.

The C standard specifies that

For two function types to be compatible [...] If one type has a parameter type list and the other type is specified by a function definition that contains a (possibly empty) identifier list, both shall agree in the number of parameters, and the type of each prototype parameter shall be compatible with the type that results from the application of the default argument promotions to the type of the corresponding identifier [...]

In this case:

  • one type has a parameter type list that specifies one parameter of type void*
  • the other type is given by a function definition that has an empty identifier list for a parameter list, and so specifies zero parameters (as opposed to not providing information about the parameters)

It follows that the two types are incompatible.

Note that this answer quotes the same passage from the standard in essentially the same situation, and yet arrives to the opposite conclusion.

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