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?
I don't think more protection can nor should be provided.
The C programming language lets you do almost everything you want freely, especially accessing objects from pointers. However, freedom is never free, so C programmers must always be careful (and avoid casting if it isn't necessary).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments