How To Read a Pointer Location In a

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
ToVa_285016
Level 5
Level 5
100 replies posted 50 replies posted 50 questions asked

 Hi,

   

I did some Googling about finding the index of a pointer in an array and tried to implement it in my code.  I have been having an issue with it.

   

The following code attempts to catch an overflow of the buffer by using the pointer index and does not work:

   

    ptrdiff_t index = dmxReadPtr - DMXbuffer;

   

    

   

    // If data ready, read data

   

    while(UART_DMX_ReadRxStatus()  & UART_DMX_RX_STS_FIFO_NOTEMPTY)

   

    {    

   

        if(index < DMX_SIZE)

   

        {

   

            *dmxReadPtr++ = UART_DMX_ReadRxData();         

   

        }

   

        else

   

        {

   

            UART_DMX_ClearRxBuffer();

   

        }

   

    }

   

The following uses an integer to index the array, and works correctly:

   

     // If data ready, read data

   

    while(UART_DMX_ReadRxStatus() & UART_DMX_RX_STS_FIFO_NOTEMPTY)

   

    {    

   

        if(place < DMX_SIZW)

   

        {

   

            DMXbuffer[place] = UART_DMX_ReadRxData();

   

        }

   

        else

   

        {

   

            UART_DMX_ClearRxBuffer();

   

        }

   

        

   

        place++;

   

    }

   

Does it have something to do with the data type of ptrdiff_t?  If so, how can I evaluate this expression?

   

Thank you,
Tom

0 Likes
2 Replies
HeLi_263931
Level 8
Level 8
100 solutions authored 50 solutions authored 25 solutions authored

Maybe I'm overlooking something, but: in your first example, you are incrementing the pointer (dmxReadPtr), but compare 'index' with the size. Thats a good recipe for a buffer overflow 🙂

0 Likes
ToVa_285016
Level 5
Level 5
100 replies posted 50 replies posted 50 questions asked

 Hi,

   

You are absolutely right.  It was a copy/paste problem that I overlooked.  The following solution works well:

   

// index of dmxReadPtr in array DMXbuffer

   

ptrdiff_t ptrIndex = 0;

   

 

   

// ISR For Break

   

CY_ISR(InterruptHandlerDMXIn)

   

{

   

    int status = 0;

   

    

   

    // Read status, and clear interrupt

   

    status = UART_DMX_ReadRxStatus();

   

    

   

    // Get location of pointer

   

    ptrIndex = dmxReadPtr - DMXbuffer;

   

    

   

    // Check for break

   

    if((status & UART_DMX_RX_STS_BREAK) != 0)

   

    {

   

        // Reset pointer

   

        dmxReadPtr = DMXbuffer;

   

        

   

        // Clear buffer

   

        UART_DMX_ClearRxBuffer();

   

    }

   

    

   

    // If data ready, read data

   

    if(status & UART_DMX_RX_STS_FIFO_NOTEMPTY)

   

    {  

   

        if(ptrIndex < DMX_SIZE)

   

        {

   

            *dmxReadPtr++ = UART_DMX_ReadRxData();

   

        }

   

    } 

   

}

   


Thank you,
Tom

0 Likes