Search code examples
objective-ccprintfnslog

sprintf fails spontaneously depending on what printf and NSLog calls there are


Hello I have a bizarre problem with sprintf. Here's my code:

void draw_number(int number,int height,int xpos,int ypos){
    char string_buffer[5]; //5000 is the maximum score, hence 4 characters plus null character equals 5
    printf("Number - %i\n",number);
    sprintf(string_buffer,"%i",number); //Get string
    printf("String - %s\n",string_buffer);
    int y_down = ypos + height;
    for (int x = 0; x < 5; x++) {
        char character = string_buffer[x];
        if(character == NULL){ //Blank characters occur at the end of the number from spintf. Testing with NULL works
            break;
        }
        int x_left = xpos+height*x;
        int x_right = x_left+height;
        GLfloat vertices[] = {x_left,ypos,x_right,ypos,x_left,y_down,x_right,y_down};
        rectangle2d(vertices, number_textures[atoi(strcat(&character,"\0"))], full_texture_texcoords);
    }
}

With the printf calls there, the numbers are printed successfully and the numbers are drawn as expected. When I take them away, I can't view the output and compare it, of-course, but the numbers aren't rendering correctly. I assume sprintf breaks somehow.

This also happens with NSLog. Adding NSLog's anywhere in the program can either break or fix the function.

What on earth is going on?

This is using Objective-C with the iOS 4 SDK.

Thank you for any answer.


Solution

  • With strcat(&character,"\0") you are trying to use a single character as a character array. This will probably result in atoi() returning completely different values from what you're expecting (as you have no null-termination) or simply crash.

    To fix the original approach, you could use proper a zero-terminated string:

    char number[] = { string_buffer[x], '\0' };
    // ...
    ... number_textures[atoi(number)] ...
    

    But even easier would be to simply use the following:

    ... number_textures[character - '0'] ...