Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc and gcc optimization 2

while(count < 30000000){
    malloc(24);
    count++;
}

the above code runs in about 170 ms on my computer compiled with gcc -O0. However, compiling with -Ox where x > 0, the optimizer cleverly figures out that the memory being requested will never be used and so it is excluded from the optimized executable. How does it do this?

like image 978
user2616927 Avatar asked Jul 27 '13 15:07

user2616927


1 Answers

Well the compiler sees malloc return value is never used so it optimizes it out. If you want to prevent malloc call to be optimzed out even in -O3 you can use the volatile qualifier:

while(count < 30000000){
    void * volatile p = malloc(24);
    count++;
}
like image 96
ouah Avatar answered Oct 22 '22 08:10

ouah