-4

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?

msc
  • 33,420
  • 29
  • 119
  • 214

1 Answers1

5

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.

msc
  • 33,420
  • 29
  • 119
  • 214
  • 5
    The quoted passages are irrelevant as the code contains a constraint violation – M.M Nov 21 '17 at 05:41