C Language Forgetting to allocate one extra byte for \0


Example

When you are copying a string into a malloced buffer, always remember to add 1 to strlen.

char *dest = malloc(strlen(src)); /* WRONG */
char *dest = malloc(strlen(src) + 1); /* RIGHT */

strcpy(dest, src);

This is because strlen does not include the trailing \0 in the length. If you take the WRONG (as shown above) approach, upon calling strcpy, your program would invoke undefined behaviour.

It also applies to situations when you are reading a string of known maximum length from stdin or some other source. For example

#define MAX_INPUT_LEN 42

char buffer[MAX_INPUT_LEN]; /* WRONG */
char buffer[MAX_INPUT_LEN + 1]; /* RIGHT */

scanf("%42s", buffer);  /* Ensure that the buffer is not overflowed */