Local Pointer Prevention

This may be a newbie question, but is there a way 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 generates a warning that the pointer cannot be returned. Now consider the following:

int* g;

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

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

This will go through the compiler without warning, which is bad. Is there any attribute or something to prevent this from happening? That is, something like:

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

Thanks in advance if anyone knows the answer.

+5
source share
2 answers

No, there is no reliable and portable way to point to a local pointer to a heap object. It is impossible to declaratively prevent this.

, , , (. ), , .

0

( ):

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

, , , 0xFDFDFDFD - , ...

if (\*((int\*)pointer-1) == 0xFDFDFD) { // stack pointer }
+2

All Articles