cstringcharoff-by-one

strncat off by one error - K&R C exercise 5-5


My version of strncat is copying one too many chars into the destination and I cannot figure out why.

#include <stdio.h>
#define MAX_CHARS 20

void nconcatenate(char *start, char *end, int n)
{
  if(sizeof start + n > MAX_CHARS)
    return;

  while(*start++);
  start--; /* now points to the final char of start, the \0 */
  int i;
  for(i = 0; (*start++ = *end++) && i < n; i++);
  *start = '\0';
}

int main()
{
  char start[MAX_CHARS] = "str";
  char *end = "ingy!";
  nconcatenate(start, end, 3);
  printf("start = %s\n", start);
  return 0;
}

Using 3 as 'n' outputs

stringy

which is one too many chars.


Solution

  • Maybe because in the condition

    (*start++ = *end++) && i < n
    

    first it does (*start++ = *end++) and after that, it checks i < n.

    I haven't tested it, but check it out and see.