Search code examples
carraysconstantsmemset

Is it legal to use memset() function on `const` array?


In the following code, elements of the const array are cleared by the memset function.

#include <stdio.h>
#include <string.h>

int main() {
    const int a[3] = {1, 2, 3};
    memset(a, 0, sizeof(a));
    printf("%d %d %d\n",a[0],a[1],a[2]);
    return 0;
}

Is it legal to use memset on const array?


Solution

  • No.

    Do not attempt to modify the contents of the array declared as const, otherwise result is undefined behavior.

    In that example, the elements of the const int a[3]; are filled by the call to memset which is generated warning because the memset function takes a (non-const) pointer to void, the compiler must implicitly cast away const.

    C11 6.7.3 Type qualifiers:

    Footnote 132:

    The implementation may place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.