Search code examples
cxcodeprintfspecifier

printf prints character instead of digit for %d specifier


On xcode c project, the code:

#include <stdio.h>

int main()
{

    int* pi = (int*) malloc(sizeof(int));
    *pi = 5;
    printf("*pi: %d\n", *pi);
    free(pi);



    return 0;
}

prints 't' , instead of 5, although I explicitly included the %specifier, that according to spec should print the signed decimal integer. I would expect the '%c' specifier would print that. What is going on?

enter image description here


Solution

  • The C dynamic memory allocation functions are defined in stdlib.h header.

    If you add the 'standard library' to your code, it should run without any errors.

    Also, malloc() returns a null pointer when it fails to allocate the space requested. So, you should make sure that what you received is not NULL by using a simple if-else block.

    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        int* pi = (int*) malloc(sizeof(int));
    
        if(pi==NULL){
           printf("Malloc Failed!");
           return -1;
        }
        else{
            *pi = 5;
            printf("*pi: %d\n", *pi);
            free(pi);
            return 0;
        }
    
    }
    

    The code block above gives the intended result *pi: 5.

    Hope this helps,

    Reference: https://en.wikipedia.org/wiki/C_dynamic_memory_allocation