Zennoxa Shield
Rules / C/C++
SHIELD-CPP-020

strncpy without null termination

mediumC/C++CWE-170CVSS 5.9

What it detects

strncpy may leave the destination without a null terminator when the source fills the buffer.

How to fix

Explicitly set the final byte to zero or use strlcpy.

Vulnerable — Shield flags thisusername.c
#include <string.h>
#include <stdio.h>

void print_username(const char *src) {
    char name[32];
    /* if src fills the buffer, name has no null terminator */
    strncpy(name, src, sizeof(name));
    printf("user: %s\n", name);
}
Fixed — scans cleanusername.c
#include <bsd/string.h>
#include <stdio.h>

void print_username(const char *src) {
    char name[32];
    /* strlcpy always null-terminates the destination */
    strlcpy(name, src, sizeof name);
    printf("user: %s\n", name);
}

Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CPP-020, the fixed one does not.

SHIELD-CPP-020: strncpy without null termination — Zennoxa Shield