free/delete union malloc/new Array in C/C++-Collection of common programming errors

It has nothing to do with the malloc() implementation. The union in your example uses the same memory location to store one of three “different” pointers. However, all pointers, no matter what they point to, are the same size – which is the native integer size of the architecture you’re on – 32 bits on 32-bit systems and 64-bits on 64-bit systems, etc. This is because a pointer is an address in memory, which may be represented by an integer.

Let’s say your arr is located at address 0x10000 (the pointer to your pointer, if you will.) Let’s say malloc() finds you a memory location at 0x666660. You assign arr.array_f to this value – which means you store the pointer 0x666660 in the location 0x10000. Then you write your floats into 0x666660 to 0x666688.

Now, you attempt to access arr.array_i. Because you’re using a union, the address of arr.array_i is the same as the address of arr.array_f and arr.array_c. So you are reading from the address 0x10000 again – and you read out the pointer 0x666660. Since this is the same pointer malloc returned earlier, you can go ahead and free it.

That said, attempting to interpret integers as text, or floating point numbers as integers, etc, will clearly lead to ruin. If arr.array_i[0] == 1, then arr.array_f[0] will definitely not == 1 and arr.array_c[0] will have no bearing on the character ‘1’. You can try “viewing” memory this way as an exercise (loop and printf()) – but you won’t achieve anything.

Originally posted 2013-11-09 23:32:21.