The const
type qualifier causes the compiler to issue an error message in case an attempt to modify an object declared as const
,but that is not enough protection.For example the following program modifies both elements of the array declared 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 to be that the compiler is not enough guard to protect the objects from being modified.How can we prevent this sort of thing?