When we defined dynamic array in C/C++ it's using head segment to keep track of number of elements in the array(in heap). for example :
int* mem = new int[8];
compiler will allocate sizeof(int)*8 bytes.
int *temp = malloc(sizeof(int)*9)
Will store "8" in the first sizeof(int) bytes and it goes like this
*temp = 8;
and then set mem address with next consecutive address respect to temp
mem = temp + 1;
Therefore,mem will points to an array of 8 elements, not 9.
And when deletion happens compiler will use mem in reverse process respect to above to deallocate memory in that heap block
delete[] mem;
My question is
If we allocate a dynamic memory which will be used in different modules in run-time and we managed to retrieve number of elements using head segment of allocated heap memory,Is it safe to use in Multi-threaded environment?
(Please assume that in each module by program design,no helper function or attribute provided to retrieve number of elements(size) in defined dynamic array.Each module only passing address(pointers) to array but not its size)
No, it is not safe in any environment. You can't rely on the compiler storing the number of elements in the array before the allocated memory, as it is not defined behavior. You should never try to get to this value.
Instead, do not even use dynamic arrays, but opt for
std::vector
.