逆向检测字符串截断 📅 2026/7/1 10:46:37 #include stdint.h #include string.h // 检查字节是否为UTF-8连续字节 (10xxxxxx) static inline int is_continuation_byte(uint8_t c) { return (c 0xC0) 0x80; } // 获取安全截断长度返回不超过dstlen的最大完整UTF-8字符长度 size_t utf8_truncate_safe(const char *src, size_t srclen, size_t dstlen) { if (dstlen srclen) return srclen; // 从截断位置向前查找直到找到UTF-8字符边界 size_t pos dstlen; while (pos 0 is_continuation_byte((uint8_t)src[pos])) { pos--; } // 检查pos位置是否是合法的UTF-8起始字节 if (pos dstlen) { // 检查是否截断了多字节字符 uint8_t c (uint8_t)src[pos]; int expected_bytes 0; if ((c 0xE0) 0xC0) expected_bytes 2; else if ((c 0xF0) 0xE0) expected_bytes 3; else if ((c 0xF8) 0xF0) expected_bytes 4; // 如果expected_bytes 0说明这是一个多字节字符的起始 // 检查这个字符是否能完整放入dst if (expected_bytes 0 pos expected_bytes dstlen) { return pos expected_bytes; } return pos; } return pos; } // 安全拷贝函数 size_t utf8_strcpy_safe(char *dst, const char *src, size_t dstlen) { if (dstlen 0) return 0; size_t copy_len utf8_truncate_safe(src, strlen(src), dstlen - 1); memcpy(dst, src, copy_len); dst[copy_len] \0; return copy_len; }