Let's use it in a multithread application, where every thread can change array's size by
1 2 3
new_p = realloc(p, new_size);
if (!new_p) exit 1;
p = new_p;
For simplify assume that we have no problems with it's size and indexing.
Question:
Expression like
int x = p[i];
is unsafe cause thread (1) takes the pointer and (2) add the index. Executing of this thread may be stoped after first step before second step. In this time other thread can realloc the array, which move it to some other place in memory. Executing second step after it will add index to wrong pointer. So we will have segmentation fault.
Is it right?
For starters.... volatile has a different meaning in C++ than it does in Java. Adding volatile here does absolutely nothing for you and does not help with multithreading at all. volatile is mostly to be used with low level memory reads/writes (ie: reading/writing to memory mapped hardware registers).
Secondly... access to any data shared between multiple threads needs to be guarded (again note: volatile does not guard for you). The easiest way to do this is by using a mutex.
If any thread needs to be able to reallocate the buffer, you will need to guard all accesses to the array. Assuming you're using C++11's STL <thread> and <mutex> headers:
std::mutex arraymutex; // declared at same scope as your array
//...
// to reallocate the array:
{
std::unique_lock( arraymutex );
p = realloc(p, new_size);
}
// to write to the array:
{
std::unique_lock( arraymutex );
p[ x ] = 0;
}
// to read from the array
int foo;
{
std::unique_lock( arraymutex );
foo = p[ x ];
}
Lastly.... why are you using malloc/realloc/free? Those have no place in C++. Just use a vector.