← All problems · Protocols & Parsing
Validate Length-Delimited Sensor Records
Each record has one type byte, one length byte and that many payload bytes. Return 1 if the entire buffer consists of complete records; empty is valid.
Implement int valid_tlv(const uint8_t *p, size_t n).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Check remaining length before accessing or advancing.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
int valid_tlv(const uint8_t *p, size_t n)
{
while(n){if(n<2)return 0; size_t len=p[1]; if(len>n-2)return 0; p+=2+len; n-=2+len;} return 1;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
int valid_tlv(const std::uint8_t *p, std::size_t n)
{
while(n){if(n<2)return 0; std::size_t len=p[1]; if(len>n-2)return 0; p+=2+len; n-=2+len;} return 1;
}
Subtracting header size only after checking avoids underflow and out-of-bounds reads.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
uint8_t a[]={1,1,42,2,0};
CHECK(valid_tlv(a,5)==1);
CHECK(valid_tlv(a,4)==0);
CHECK(valid_tlv(a,1)==0);
CHECK(valid_tlv(a,0)==1);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}