Is it secure to do the following?
MyClass* p = WantItInCase1();
if (p == NULL)
p = 0x1;
else
p = WantItInCase2();
if (p == NULL)
p = 0x2;
...
CheckCases (p); // we check '0x1' and '0x2' cases and otherwise process 'p' as normal object
I have a situation where MyClass objects can’t handle all variants needed in CheckCases(). So to avoid additional parameter is it possible to use this approach? At least I need a range of addresses that can’t be used for new allocations.
— Update —
Taking in account answers I decided to make some ‘tricky’ approach:
// somewhere in global definitions:
const MyClass* P_CASE_1 = (MyClass*) new int;
const MyClass* P_CASE_2 = (MyClass*) new int;
...
// previous code piece:
MyClass* p = WantItInCase1();
if (p == NULL)
p = P_CASE_1;
It would be memory-safe, and it’s not dangerous to leak 4 bytes for each P_CASE_#.
It depends on the OS 🙂
To make it clear: on Windows 32 bits the last gb of address space is always reserved for the kernel, so you can use its addresses for your use. Normally it would be the last 2 gb of address space, but through a switch /3GB you can change it. A similar trick is used in the kernel for some data structures.
I wouldn’t ever do it 🙂
I’ll add that probably 0x1, 0x2, 0x3 are pretty safe, because the addresses given to you by the OS are normally at least 32 bits aligned, the 0x0 is defined for special purpose so the next three bytes won’t be allocated in a memory block. Aaah… Too much difficult to explain. Let’s say that the C runtime takes the memory from the OS, and that “standard” OS won’t ever give memory in the 0x0-0x3 range.