I'm working on my hobby project in c++, and want to test a continuous memory allocation for variables of different types, (Like array with variables of different types). How can i check if a specific memory address is available for use?
More Details:
Let's say we've got the following code: we have an integer int_var
, (it doesn't matter in which memory address this variable seats), In order to allocate a variable of different type in the address right after the address of int_var
i need to check if that address is available and then use it. i tried the following code:
int int_var = 5;
float* flt_ptr = (float*)(&int_var + (sizeof(int_var) / sizeof(int)));
// check if flt_ptr is successfully allocated
if (flt_ptr) { // successfully allocated
// use that address
} else { // not successfully allocated
cout << "ERROR";
}
The problem is: When i run the program, sometimes flt_ptr
is successfully allocated and all right, and sometimes not - but when it is not successfully allocated it throws an exception that says "Read access violation ..." instead of printing "ERROR"
. Why is that? Maybe i missed something about checking if flt_ptr
is successfully allocated? Or did something wrong? If so, How do i check if flt_ptr
is successfully allocated before i use it?
Thanks!!