alloca allocate memory on stack , 有以下優點 :
• There is very little overhead to the allocation process because the microprocessor
has hardware support for the stack.
• The memory space never becomes fragmented thanks to the first-in-last-out nature
of the stack.
• Deallocation has no cost because it goes automatically when the function returns.
There is no need for garbage collection.
• The allocated memory is contiguous with other objects on the stack, which makes
data caching very efficient.
例子:
#include <alloca.h>
p = (int*) alloca(1000*sizeof(int)) ;
int i ;
for(i=0;i<1000;i++)
p[i] = i ;
另外 , 如果想要 allocate aligned memory location on heap , 可參考以下片段 :
int res;
int *ptr[10] ;
res = posix_memalign((void **)&(ptr[0]) , 64, 10*64);
if (NULL != ptr[0])
{
int idx ;
for(idx=0;idx<10;idx++)
{
ptr[idx] = (int*) ((char*)ptr[0] + idx*64 );
*(ptr[idx]) = idx * idx * idx + 1 ;
}
for(idx=0;idx<10;idx++)
{
printf("(%d)\n",*(ptr[idx]) ) ;
}
}
(1)
(2)
(9)
(28)
(65)
(126)
(217)
(344)
(513)
(730)
Method2 :
struct s_ { char x[64]; } __attribute__ (( __aligned__( 64 ) ));
typedef struct s_ S ;
S x[10] ;
int *ptr[10] ;
int idx ;
for(idx=0;idx<10;idx++)
{
ptr[idx] = (int*) &(x[idx]) ;
*(ptr[idx]) = idx * idx * idx + 1 ;
}
for(idx=0;idx<10;idx++)
{
printf("(%p)(%d)\n",&(x[idx]),*(ptr[idx]) ) ;
}
(0x7fff3f9bfa40)(1)
(0x7fff3f9bfa80)(2)
(0x7fff3f9bfac0)(9)
(0x7fff3f9bfb00)(28)
(0x7fff3f9bfb40)(65)
(0x7fff3f9bfb80)(126)
(0x7fff3f9bfbc0)(217)
(0x7fff3f9bfc00)(344)
(0x7fff3f9bfc40)(513)
(0x7fff3f9bfc80)(730)
留言列表