Reserving Space for the Null Character
suggest changeThe result of strlen does not include the terminating null character. A buffer that will hold a copy of a string therefore needs one additional byte:
size_t length = strlen(src);
char *dest = malloc(length + 1);
if (dest != NULL) {
memcpy(dest, src, length + 1);
}
Allocating only strlen(src) bytes and then copying the complete string writes past the allocation and has undefined behavior.
The same rule applies when reserving space for input. A field width for scanf limits the number of input characters; the function then appends a null character:
#define MAX_INPUT_LEN 42
char buffer[MAX_INPUT_LEN + 1];
if (scanf("%42s", buffer) == 1) {
/* buffer contains a null-terminated word */
}
%s stops at whitespace. Use fgets when spaces should be preserved or when line-oriented input is more appropriate.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents