user5619103
user5619103

Reputation:

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

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?

Upvotes: 7

Views: 216

Answers (3)

Afshin
Afshin

Reputation: 392

I think the philosophy behind protection is the comfort of one who is using your code as ready library in his own code. Otherwise if it was possible to make the object completely non-modifiable in C language, there would be some crackers who could modify whatever they want :) :)

Upvotes: 0

anatolyg
anatolyg

Reputation: 28239

A standard tool for finding memory overruns is watchpoints, or data breakpoints as they are called in MS Visual Studio.

If you need to protect your object just for debugging, use your debugger to set a watchpoint inside your object. The bug will be discovered at runtime (not compile time) - when your program tries to write to the specified address, the debugger will stop it.

You might be able to set your watchpoints in your code, but their number is limited (the maximum is 4 on x86 platform), so this cannot be a general-purpose feature of your program.

Upvotes: 0

nalzok
nalzok

Reputation: 16097

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).

Upvotes: 3

Related Questions