Is reusing a memory location safe?
<p>This question is based on some existing C code ported to C++. I am just interested in whether it is "safe". I already know I wouldn't have written it like this. I am aware that the code here is basically C rather than C++ but it's compiled with a C++ compiler and I know that the standards are slightly different sometimes.</p>

<p>I have a function that allocates some memory. I cast the returned <code>void*</code> to an <code>int*</code> and start using it.</p>

<p>Later on I cast the returned <code>void*</code> to a <code>Data*</code> and start using that.</p>

<p>Is this safe in C++?</p>

<p>Example :-</p>

<pre><code>void* data = malloc(10000);

int* data_i = (int*)data;
*data_i = 123;
printf("%d\n", *data_i);

Data* data_d = (Data*)data;
data_d-&gt;value = 456;
printf("%d\n", data_d-&gt;value);
</code></pre>

<p>I never read variables used via a different type than they were stored but worry that the compiler might see that <code>data_i</code> and <code>data_d</code> are different types and so cannot legally alias each other and decide to reorder my code, for example putting the store to <code>data_d</code> before the first <code>printf</code>. Which would break everything.</p>

<p>However this is a pattern that is used all the time. If you insert a <code>free</code> and <code>malloc</code> in between the two accesses I don't believe it alters anything as it doesn't touch the affected memory itself and can reuse the same data.</p>

<p>Is my code broken or is it "correct"? </p>