title: Multiplatform build - snprintf fails in C
body: <p>I am learning C and trying to make sure my code is portable. For that effect, I build on Macs (ARM, PPC, Intel), Linux (ARM, PPC, PA-RISC) and HP-UX (PA-RISC).
  To make sure I have an easy way to output simple graphics, I am using GLUT.</p>
  <p>I have the following code and functions:</p>
  <pre><code>GLfloat white[3] = { 1.0, 1.0, 1.0 };
  GLfloat red[3] = { 1.0, 0.0, 0.0 };
  GLfloat green[3] = { 0.0, 1.0, 0.0 };
  
  void printText(char *text, const GLfloat colour[3], float posX, float posY) {
      glColor3fv (colour);
      glRasterPos2f(posX, posY); //define position on the screen
        
      while(*text){
        glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *text++);
      }
  }
  
  void GLprintTextAndInteger (char *text, int value, float colour[3], float posX, float posY) {
      int length = snprintf(NULL, 0, &quot;%s %i&quot;, text, value);
      char *stringToPrint = malloc(length + 1);
      snprintf(stringToPrint, length + 1, &quot;%s %i&quot;,text,value);
      printText(stringToPrint,colour,posX,posY);
      free(stringToPrint);
  }
  
  void GLprintTextAndLong (char *text, long value, float colour[3], float posX, float posY) {
      int length = snprintf(NULL, 0, &quot;%s %ld&quot;, text, value);
      char *stringToPrint = malloc(length + 1);
      snprintf(stringToPrint, length + 1, &quot;%s %ld&quot;, text, value);
      printText(stringToPrint,colour,posX,posY);
      free(stringToPrint);
  }
  </code></pre>
  <p>Which I call as follows, for example:</p>
  <pre><code>GLprintTextAndInteger(&quot;sample text&quot;, int whatever, white, -0.98f, 0.1f);
  GLprintTextAndLong(&quot;sample text&quot;, long whatever, white, -0.98f, 0.0f);
  printText(&quot;some text&quot;,white,-0.98f,-0.1f);
  </code></pre>
  <p>When I build on HP-UX, using both HP's compiler and also GCC, when I run the program, only printText works. GLprintTextAndInteger and GLprintTextAndLong do nothing (or maybe they work, but are black and then I can't see the output). The code builds without any warnings in all platforms. It runs perfectly well on Linux and Mac, in all architectures.</p>
  <p>Any suggestions?</p>
  <p>Edit:</p>
  <p>During troubleshooting, I found out that if I replace:</p>
  <pre><code>int length = snprintf(NULL, 0, &quot;%s %i&quot;, text, value);
  </code></pre>
  <p>with</p>
  <pre><code>int length = 40;
  </code></pre>
  <p>it works fine. Why is snprintf failing?</p>