format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ [-Wformat]

Optimus Prime picture Optimus Prime · Oct 13, 2012 · Viewed 42.6k times · Source

I have searched about this warning and everyone had some mistake in their code, but here is something very unexpected I could not figure out . We do expect strlen(x) to be an integer but what does this warning tell me? How couldn't strlen be int?

In function ‘fn_product’:
line85:3:warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ [-Wformat]

My code in fn_product --

char *fn_product (char x[],char y[]){
  if (strlen(x)==1)    // line85
    printf("\nlength of string--%d\n", strlen(x));
  /*other code*/
}

Shouldn't strlen(x) be int.Why does it say to be of format size_t?

Answer

Carl Norum picture Carl Norum · Oct 13, 2012

Did you check the man page? strlen(3) returns size_t. Use %zu to print it.

As mentioned in the comments below, clang is sometimes helpful with finding better error messages. clang's warning for exactly this case is pretty great, in fact:

example.c:6:14: warning: format specifies type 'unsigned int' but the argument
      has type 'size_t' (aka 'unsigned long') [-Wformat]
    printf("%u\n", strlen("abcde"));
            ~^     ~~~~~~~~~~~~~~~
            %zu
1 warning generated.