Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing local pointers

Maybe it's a newbie question, but is there a method in C/C++ to prevent a function from accepting a pointer to a local variable?

Consider this code:

int* fun(void)
{
 int a;
 return &a;
}

The compiler will generate a warning that the pointer can not be returned. Now consider this:

int* g;

void save(int* a)
{
 g = a;
}

void bad(void)
{
 int a;
 save(&a);
}

This will pass through the compiler without a warning, which is bad. Is there an attribute or something to prevent this from happening? I.e. something like:

void save(int __this_pointer_must_not_be_local__ * a)
{
 g = a;
}

Thanks in advance if someone knows the answer.

like image 467
haael Avatar asked Nov 04 '22 22:11

haael


1 Answers

There is at least one way for debug build using debug heap (default):

//d:\Program Files\Microsoft Visual Studio ?\VC\crt\src\dbgint.h
\#define nNoMansLandSize 4
typedef struct _CrtMemBlockHeader
{
    struct _CrtMemBlockHeader * pBlockHeaderNext;
    struct _CrtMemBlockHeader * pBlockHeaderPrev;
    char *                      szFileName;
    int                         nLine;
    size_t                      nDataSize;
    int                         nBlockUse;
    long                        lRequest;
    unsigned char               gap[nNoMansLandSize];
    /* followed by:
     *  unsigned char           data[nDataSize];
     *  unsigned char           anotherGap[nNoMansLandSize];
     */
} _CrtMemBlockHeader;
\#define pbData(pblock) ((unsigned char *)((_CrtMemBlockHeader *)pblock + 1))

There is a allocation header, which ends with gap, so there is not big probability there will be 0xFDFDFDFD before the pointer - not perfect, but may help...

if (\*((int\*)pointer-1) == 0xFDFDFD) { // stack pointer }
like image 149
El Tom Avatar answered Nov 09 '22 14:11

El Tom