PartTimeEngineer
PartTimeEngineer

Reputation: 33

understanding function(const int *a ) pointer to integer constant

We are able to modify the value of constant integer pointer by b, how can we make sure/restrict accidentally modification of the value ?

 #include <stdio.h>

/**
 * Snippet to under working of "pointer to integer(any) constant"
 * 
 * We are able to modify the value of constant integer pointer by b, how 
 * can we make sure/restrict accidentally modification of the value .
 * 
 */

void modify_value(const int *m, const int *n) {
    //*m = 50;         // expected error, assignment of read-only location
    *((int*)n) = 100;  // value of pointed by pointer gets updated !! 
}   

int main() {
    int a=5,b=10;
    printf("a : %d , b : %d \n", a,b);
    modify_value(&a,&b);
    printf("a : %d , b : %d \n", a,b);
    return 0;
}

Upvotes: 2

Views: 96

Answers (1)

skyking
skyking

Reputation: 14360

As far as I know there's no waterproof way to prevent this, but there are ways to avoid this by mistake.

For example some compilers have warnings and you can even make warnings into error (ie fail to compile if a warning is triggered). For example on GCC you can use -Wcast-qual and -Werror (or -Werror=cast-qual). But this will not completely prevent you from modifying data pointed to by const *, as with many warnings there are ways to work around them. For example you could on some platform cast via an integral type, for example (int*)((char const*)m - (char*)NULL), but note that this is not a portable construct (but I think the casting away constness is a non-portable construct anyway).

If you want to go a bit further you could of course recompile GCC to better keep track on qualifiers and prohibit some of these workarounds, but that might be at the cost of dropping standard conformance.

Another solution would be to use some kind of lint tool. These often can emit warnings that normal compilers pass. Also in your build scripts you can normally make these lint-warnings to be considered build errors (and not compile a file that has lint warnings).

Upvotes: 3

Related Questions