Search code examples
ccallocstrncpynul

Relation between calloc char array and null terminating character


This whole "debate" on the web about strncpy being safe vs unsafe is driving me crazy. I find some people saying strncpy is the "devil", which to me sounds like they lack the programming discipline. I get that there is no \0 character added to the end of dest when the src is greater than the dest (which ultimately causes problems). I've heard of strlcpy, but from what I gather it's not standard. I want my code to be as portable as possible, so I don't consider this a viable solution.

Here is my current solution...

First define the buffer size

#define BUFSIZE 1024

Within the program, allocate the buffer using calloc

char *buffer;

buffer = calloc(BUFSIZE+1, sizeof(char));

Then later in the code, lets say I want to copy msg to buffer and I use

strncpy(buffer,msg,BUFSIZE);

Since I preallocated buffer with BUFSIZE + 1 then this ensures that the last byte of buffer is \0 regardless if msg is greater than BUFSIZE.

Now the question is, does calloc initialize the character array with \0? Is it wrong to interpret the zero allocation of calloc to be the same as \0?


Solution

  • Clearing the array to 0 will fill all characters to \0.

    So '\0' is completely equivalent to an unadorned 0 integer constant - the only difference is in the intent that it conveys to a human reader ("I'm using this as a null character.").

    See What is the difference between NULL, '\0' and 0