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.
I have the following code and functions:
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, "%s %i", text, value);
char *stringToPrint = malloc(length + 1);
snprintf(stringToPrint, length + 1, "%s %i",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, "%s %ld", text, value);
char *stringToPrint = malloc(length + 1);
snprintf(stringToPrint, length + 1, "%s %ld", text, value);
printText(stringToPrint,colour,posX,posY);
free(stringToPrint);
}
Which I call as follows, for example:
GLprintTextAndInteger("sample text", int whatever, white, -0.98f, 0.1f);
GLprintTextAndLong("sample text", long whatever, white, -0.98f, 0.0f);
printText("some text",white,-0.98f,-0.1f);
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.
Any suggestions?
Edit:
During troubleshooting, I found out that if I replace:
int length = snprintf(NULL, 0, "%s %i", text, value);
with
int length = 40;
it works fine. Why is snprintf failing?