Printf/scanf with size_t

Alec Jacobson

May 12, 2011

weblog/

I was recently bamboozled by my own code when I switched from compiling for 32-bits (i386) to 64-bits (x86_64). I had a bunch of scanf/printf lines reading and printing size_t variables. Here's a test program in C++ that demonstrates the correct usage of the z option for reading in size_t:
#include <cstdio>
#include <limits>


int main(int argc,char * argv[])
{
  // Show size of size_t
  printf("sizeof(size_t): %lu\n",(long unsigned int)(sizeof(size_t)));
  // Show max size_t value: (2^8)^sizeof(size_t)
  long unsigned int max_size_t = std::numeric_limits<std::size_t>::max();
  printf("max_size_t: %lu\n",max_size_t);
  // read into size_t
  size_t a;
  int nr = sscanf(argv[1],"%zu",&a);
  // print size_t
  printf("argv[1]: %zu\n",a);
  return 0;
}