How can I ensure that the value in uIndexFound don't underflow? What should I change?…
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
How can I ensure that the value in uIndexFound don't underflow? What should I change? """ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <string.h>
#define RING_BUFFER_LEN (100)
#define INCREMENT_BUFFER_INDEX( idx, inc ) ((idx) = ((idx) + (inc)) % RING_BUFFER_LEN)
typedef struct _RingBuffer { char buf[RING_BUFFER_LEN]; uint16_t head, tail; } RingBuffer;
uint16_t RingBuffer_GetDataLength( RingBuffer *rb ) { return (rb->head < rb->tail) ? (RING_BUFFER_LEN - (rb->tail - rb->head)) : (rb->head - rb->tail); }
bool RingBuffer_SearchString( RingBuffer *rb, uint16_t uTailOffset, char *sString, uint16_t uStringLen, uint16_t *uIndexFound ) { uint16_t uDataLen = RingBuffer_GetDataLength( rb );
codeuTailOffset %= RING_BUFFER_LEN; // crop offset if( (uStringLen == 0) || (uTailOffset + uStringLen > uDataLen) ) return false; /* create bad match table */ uint16_t uBadMatchTable[256]; for( uint16_t i = 0; i < 256; i++ ) uBadMatchTable[i] = uStringLen; for( uint16_t i = 0; i < (uStringLen - 1); i++ ) uBadMatchTable[(uint8_t)(sString[i])] = uStringLen - 1 - i; /* search sub-string */ uint16_t uPos = uTailOffset + uStringLen - 1; while( uPos < uDataLen ) { uint16_t uTempTail, uMatches = 0; while( uMatches < uStringLen ) { uTempTail = rb->tail; INCREMENT_BUFFER_INDEX( uTempTail, uPos - uMatches ); printf("%s\n", &(rb->buf[uTempTail]) ); if( rb->buf[uTempTail] != sString[uStringLen - 1 - uMatches] ) uMatches = uStringLen; // exit while loop with an error uMatches++; } if( uMatches == uStringLen ) { *uIndexFound = rb->tail; INCREMENT_BUFFER_INDEX( *uIndexFound, uPos - uStringLen ); return true; } uTempTail = rb->tail; INCREMENT_BUFFER_INDEX( uTempTail, uPos ); uPos += uBadMatchTable[(uint8_t)(rb->buf[uTempTail])]; } return false; - Assistant
To prevent the
uIndexFoundvariable from underflowing, you need to adjust the calculation where you're incrementinguIndexFoundby the position of the found string in the ring buffer. Specifically, you should change the line:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.