cpointerscharmallocconversion-specifier

Is the default value of malloc with the size of a single char P?


char *ptr = malloc(sizeof(char));
printf("\nValue of ptr: %d\n",ptr);
printf("\nValue of address of ptr: %x\n",&ptr);
printf("\nValue of pointed by ptr: %c\n",*ptr);
printf("\nValue of address pointed by ptr: %x\n",&(*ptr));
*ptr='u';
 printf("\nValue of pointed by ptr: %c\n",*ptr);
printf("\nValue of address pointed by ptr: %x\n",&(*ptr));

In the above piece of code, the following output is received:

Value of ptr: 1046113600
Value of address of ptr: a2fffa78
Value of pointed by ptr: P
Value of address pointed by ptr: 3e5a6d40
Value of pointed by ptr: u
Value of address pointed by ptr: 3e5a6d40

Does this imply that the default value of the malloc with a single char size is P?

Tried to allocate memory of single char size using malloc and initialized a pointer pointing to the allocated memory. Tried to print the value of the allocated memory.


Solution

  • malloc allocates memory without initializing it. So the allocated memory can contain any set of bit values. Neither default value is used.

    Opposite to malloc you can use another allocating function calloc that zero initializes the allocated memory as for example

    char *ptr = calloc(1, sizeof(char));
    

    Pay attention to that such calls of printf to output values of pointers like

    printf("\nValue of ptr: %d\n",ptr);
    printf("\nValue of address of ptr: %x\n",&ptr);
    

    are invalid and have undefined behavior. In particularly for example the conversion specifier d is designed to output integers of the type int and sizeof( int ) can be equal to 4 while sizeof( char * ) can be equal to 8.

    From the C Standard (7.21.6.1 The fprintf function)

    9 If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

    You should use either the conversion specifier p with pointers as for example

    printf("\nValue of ptr: %p\n", ( void * )ptr);
    

    or conversion specifiers defined in header <inttypes.h>

    #include <inttypes.h>
    
    //...
    
    printf("\nValue of ptr: %" PRIdPTR "\n", ( intptr_t )( void * )ptr);