A qualifier of type const causes the compiler to give an error message in case of an attempt to modify an object declared as const , but this is not enough for protection. For example, the following program modifies both elements of a declared array as const :
#include <stdio.h> int main(void) { const char buf[2] = { 'a','b' }; const char *const ptr = buf; unsigned long addr = (unsigned long)ptr; *(char *)addr = 'c'; addr = addr + 1; *(char *)addr = 'd'; printf("%c\n", buf[0]); printf("%c\n", buf[1]); return 0; }
So, it turns out that the compiler is not secure enough to protect objects from modification. How can we prevent such a thing?
c
user5619103
source share