Search code examples
gccmemory-managementconstants

Protecting memory from changing


Is there a way to protect an area of the memory?

I have this struct:

#define BUFFER 4
struct
{
    char s[BUFFER-1];
    const char zc;
} str = {'\0'};

printf("'%s', zc=%d\n", str.s, str.zc);

It is supposed to operate strings of lenght BUFFER-1, and garantee that it ends in '\0'.

But compiler gives error only for:

str.zc='e'; /*error */

Not if:

str.s[3]='e'; /*no error */

If compiling with gcc and some flag might do, that is good as well.

Thanks, Beco


Solution

  • To detect errors at runtime take a look at the -fstack-protector-all option in gcc. It may be of limited use when attempting to detect very small overflows like the one your described.

    Unfortunately you aren't going to find a lot of info on detecting buffer overflow scenarios like the one you described at compile-time. From a C language perspective the syntax is totally correct, and the language gives you just enough rope to hang yourself with. If you really want to protect your buffers from yourself you can write a front-end to array accesses that validates the index before it allows access to the memory you want.