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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With