这是align_malloc()的正确实现吗?

时间:2016-10-02 12:02:58

标签: c++ c memory-management alignment allocation

为了提高性能,我试图实现一个aligned_malloc()函数来分配带有对齐地址的新内存,我知道“new”运算符总是返回一个对齐的地址,但我想编写自己的函数以便更好地理解,这个是我的尝试:

#include <iostream>
#include <stdlib.h>
/*
in purpose let's make our struct not aligned
*/
struct s{
        char foo[3]; 
};
s * array = NULL;
template <class t>
t* aligned_malloc(size_t array_size)
{
    t* array = NULL;
    char * ptr = (char*)  malloc((array_size+1)*sizeof(t)); // array_size+1 to not get out of memory when incrementing pointer
    while((((uintptr_t)ptr)%sizeof(t)) != 0 )
    ++ptr;
    return ((t*)ptr); 
}
int main()
{
    struct s * array = aligned_malloc<s>(10);
    /*
    let's test for crashs 
    */
    for (int c=0;c<10;c++)
    {
        array[c].foo[3] = 'f';
     }
    std::cout<<(((int)array)%sizeof(s))<<std::endl; // allways show '0' ,like the operator "new"
    system("pause");

}

另一种方法是创建一个内存管理器,分配一个大内存块并返回每个请求的对齐地址。

注意:我不假设这是正确的方法,我为了学习目的写了这个,而不是假设&amp;没有声称。

0 个答案:

没有答案