What is the correct way to allocate memory that is defined as volatile
so that all standard compilers will not optomise out writes to the
memory that are never read again?
What compiler are you using? How are you writing to the memory?
Here's a simple program:
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *x = malloc(128);
memset(x, 0, 128);
free(x);
return 0;
}
Here's the start of the code produced by gcc with -O3 optimization
level:
0x080483e0 <main+0>: lea ecx,[esp+0x4]
0x080483e4 <main+4>: and esp,0xfffffff0
0x080483e7 <main+7>: push DWORD PTR [ecx-0x4]
0x080483ea <main+10>: push ebp
0x080483eb <main+11>: mov ebp,esp
0x080483ed <main+13>: sub esp,0x18
0x080483f0 <main+16>: mov DWORD PTR [ebp-0x8],ecx
0x080483f3 <main+19>: mov DWORD PTR [ebp-0x4],ebx
0x080483f6 <main+22>: mov DWORD PTR [esp],0x80
0x080483fd <main+29>: call 0x8048340 <malloc@plt>
0x08048402 <main+34>: mov DWORD PTR [esp+0x8],0x80
0x0804840a <main+42>: mov DWORD PTR [esp+0x4],0x0
0x08048412 <main+50>: mov ebx,eax
0x08048414 <main+52>: mov DWORD PTR [esp],eax
0x08048417 <main+55>: call 0x8048310 <memset@plt>
0x0804841c <main+60>: mov DWORD PTR [esp],ebx
0x0804841f <main+63>: call 0x8048330 <free@plt>
Notice that even on the highest optimization level, gcc doesn't remove
the call to memset, even with no volatile qualifiers around, and even
though the memory is immediately free()d afterwards.