Search code examples
pointerssizeofcalloc

unexpected output while using strlen function


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char *p;
    p=calloc(10,sizeof(char));
    printf("the address of pointer is %p and size of the string is %d",p,strlen(p));
    return 0;
}

I allocated 10 bytes of memory in heap using calloc and i expect the output of size will be 10 but the output is

the address of pointer is 0x123e010 and size of the string  is 0

why the size is 0 and not 10


Solution

  • strlen simply counts the number of bytes whose value are not 0x00 (also known as NULL, which the C standard uses for string terminator).

    Since calloc initializes memory to 0x00 after allocating it, strlen returns 0 because the first byte is already NULL.