Is there a way (actually) to protect an object from modification?

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?

+7
c
source share
3 answers

I do not think that protection will be granted and .

The C programming language allows you to do almost anything you want freely, especially accessing objects from pointers. However, freedom is never free, so C programmers should always be careful (and avoid casting if this is not necessary).

+3
source share

The standard tool for finding memory overflows is observation points or data breakpoints, as they are called up in MS Visual Studio.

If you need to protect your object for debugging only, use the debugger to set the watchpoint inside your object. An error will be detected at runtime (not compilation time) - when your program tries to write to the specified address, the debugger will stop it.

You can set your watchpoints in your code , but their number is limited (maximum 4 on the x86 platform), so this may not be a common function of your program.

0
source share

I think the security philosophy is the comfort of someone who uses your code as a ready-made library in their own code. Otherwise, if it were possible not to completely modify the object in C, there would be some crackers that could change everything they want :) :)

0
source share

All Articles