Search code examples
cvolatilexc32

C string standard library, memset and discarded volatile keyword


I'm getting warning like this on xc32 compiler (gcc based microcontroller compiler, not open-source).

modem_uart.c:66:5: warning: passing argument 1 of 'memset' discards 'volatile' qualifier from pointer target type [enabled by default]

Here is the code:

#include <string.h>
// (...)
volatile char rxbuf[MODEM_UART_RXBUF_SIZE];
// (...)

void some_function(void)
{    
    // (...)
    memset(rxbuf, 0, MODEM_UART_RXBUF_SIZE); // <- warning here
    // (...)
}

Can someone explain why compiler is discarding volatile?


Solution

  • The specification in the standard of memset has the following declaration:

    void *memset(void *s, int c, size_t n);
    

    The first argument is not declared volatile void *s. So it doesn't guarantee to obey the extra restrictions on accessing volatile data. Making every call to memset() treat the destination as if were volatile would impose an unnecessary performance impact.

    If you need those assurances, you should replace the memset() call with an explicit loop.

    for (int i = 0; i < MODEM_UART_RXBUF_SIZE; i++) {
        rxbuf[i] = 0;
    }
    

    If you need this from multiple places in your code, you could put it into a volatile_memset() function.