2

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?

ThatsRightJack
  • 721
  • 6
  • 29
  • From http://www.cplusplus.com/reference/cstdlib/calloc/: "Allocate and zero-initialize array". `\0` just means "the character represented by the integer 0". – Scott Hunter Jun 27 '18 at 00:46
  • 1
    in this case `calloc` is useless as you change the value of your string completely just use `malloc`. – Stargateur Jun 27 '18 at 01:14
  • I believe I'm only changing the first `BUFSIZE` elements of the string. The point of `calloc` (with BUFSIZE+1) was to ensure the last element is `0`, from which I gather in the solution is equal to `\0`. This means the string will always have a nul terminating character. `malloc` does not initialize the array with zeros, hence why I didn't use it. – ThatsRightJack Jun 27 '18 at 01:36
  • 1
    Or you could use `malloc` and assign the only `\0` that matters. – Scott Hunter Jun 27 '18 at 02:09
  • Yeah, I suppose I could do that. – ThatsRightJack Jun 27 '18 at 02:11

1 Answers1

2

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

chf2117
  • 166
  • 9