在分配了new []的阵列上使用avx时出现分段错误(核心转储)

时间:2019-04-08 04:29:31

标签: c++11 codeblocks intrinsics avx

当我在Visual Studio 2015中运行此代码时,代码可以正常运行,但是代码在代码块中生成以下错误:分段错误(核心已转储)。我也用同样的错误在ubuntu中运行了代码。

#include <iostream>
#include <immintrin.h>

struct INFO
{
    unsigned int id = 0;
    __m256i temp[8];
};

int main()
{
    std::cout<<"Start AVX..."<<std::endl;
    int _size = 100;
    INFO  *info = new INFO[_size];
    for (int i = 0; i<_size; i++)
    {
        for (int k = 0; k < 8; k++)
        {
            info[i].temp[k] = _mm256_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
                20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31);

        }
    }
    std::cout<<"End AVX."<<std::endl;
    return 0;
}

2 个答案:

答案 0 :(得分:5)

问题在于,在C ++ 17之前的newdelete并不尊重待分配类型的对齐方式。如果您通过此简单函数查看生成的程序集:

INFO* new_test() {
    int _size = 100;
    INFO  *info = new INFO[_size];
    return info;
}

您会看到,使用C ++ 17之前的任何内容进行编译时,会调用operator new[](unsigned long),而对于C ++ 17,则会调用operator new[](unsigned long, std::align_val_t)(而32是为第二个参数传递)。 Play around with it at godbolt

如果您不能使用C ++ 17,则可以覆盖operator new[](和operator delete[] -并且还应该覆盖operator newoperator delete .. ):

struct INFO {
    unsigned int id = 0;
    __m256i temp[8];
    void* operator new[](size_t size) {
        // part of C11:
        return aligned_alloc(alignof(INFO), size);
    }
    void operator delete[](void* addr) {
        free(addr); // aligned_alloc is compatible with free
    }
};

如果您使用-DOVERWRITE_OPERATOR_NEW进行编译,则这是上一个示例的一部分。

请注意,在使用std::vector(或任何其他std-容器)时,这不能解决对齐问题,因为您需要将对齐的分配器传递给容器(不是先前的一部分)例如)。

答案 1 :(得分:0)

I found two ways to solve this problem

The first solution How to solve the 32-byte-alignment issue for AVX load/store operations?

struct INFO
{
    __m256i temp[8];
    unsigned int id = 0;
};
INFO  *info = static_cast<INFO*>(_mm_malloc(sizeof(INFO)*_size, 32));
_mm_free(info);

The second solution

INFO  *info = new INFO[_size];
for (int i = 0; i < _size; i++)
{
    INFO new_info;
    for (int k = 0; k < 8; k++)
    {
        new_info.temp[k] = _mm256_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
            20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31);

    }
    info[i] = new_info;
}