gpt4 book ai didi

c++ - 编译器忽略 operator new 分配

转载 作者:太空宇宙 更新时间:2023-11-04 14:46:56 26 4
gpt4 key购买 nike

我正在用 C++ 编写一个 512 位整数。对于整数,我使用 new 关键字从堆中分配内存,但编译器(MINGW 上的 g++ 8.1 版)似乎错误地优化了它。即编译器命令是:

g++ -Wall -fexceptions -Og -g -fopenmp -std=c++14 -c main.cpp -o main.o

g++ -o bin\Debug\cs.exe obj\Debug\main.o -O0 -lgomp

代码:

#include <iostream>
#include <cstdint>
#include <omp.h>

constexpr unsigned char arr_size = 16;
constexpr unsigned char arr_size_half = 8;
void exit(int);

struct uint512_t{
uint32_t * bytes;
uint512_t(uint32_t num){
//The line below is either (wrongfully) ignored or (wrongfully) optimized out
bytes = new(std::nothrow) uint32_t[arr_size];
if(!bytes){
std::cerr << "Error - not enough memory available.";
exit(-1);
}
*bytes = num;
for(uint32_t * ptr = bytes+1; ptr < ptr+16; ++ptr){
//OS throws error 0xC0000005 (accessing unallocated memory) here
*ptr = 0;
}
}
uint512_t inline operator &(uint512_t &b){
uint32_t* itera = bytes;
uint32_t* iterb = b.bytes;
uint512_t ret(0);
uint32_t* iterret = ret.bytes;
for(char i = 0; i < arr_size; ++i){
*(iterret++) = *(itera++) & *(iterb++);
}
return ret;
}

uint512_t inline operator =(uint512_t &b){
uint32_t * itera=bytes, *iterb=b.bytes;
for(char i = 0; i < arr_size; ++i){
*(itera++) = *(iterb++);
}
return *this;
}
uint512_t inline operator + (uint512_t &b){
uint32_t * itera = bytes;
uint32_t * iterb = b.bytes;
uint64_t res = 0;
uint512_t ret(0);
uint32_t *p2ret = ret.bytes;
uint32_t *p2res = 1+(uint32_t*)&res;
//#pragma omp parallel for shared(p2ret, res, p2res, itera, iterb, ret) private(i, arr_size) schedule(auto)
for(char i = 0; i < arr_size;++i){
res = *p2res;
res += *(itera++);
res += *(iterb++);
*(p2ret++) = (i<15) ? res+*(p2res) : res;
}
return ret;
}
uint512_t inline operator += (uint512_t &b){
uint32_t * itera = bytes;
uint32_t * iterb = b.bytes;
uint64_t res = 0;
uint512_t ret(0);
uint32_t *p2ret = ret.bytes;
uint32_t *p2res = 1+(uint32_t*)&res;
//#pragma omp parallel for shared(p2ret, res, p2res, itera, iterb, ret) private(i, arr_size) schedule(auto)
for(char i = 0; i < arr_size;++i){
res = *p2res;
res += *(itera++);
res += *(iterb++);
*(p2ret++) = (i<15) ? res+(*p2res) : res;
}
(*this) = ret;
return *this;
}
//uint512_t inline operator * (uint512_t &b){
//}
~uint512_t(){
delete[] bytes;
}
};

int main(void){
uint512_t a(3);
}

最佳答案

ptr < ptr+16总是正确的。循环是无限的,最终会溢出它写入的缓冲区。

简单的解决方案:值初始化数组,这样你就不需要循环了:

bytes = new(std::nothrow) uint32_t[arr_size]();
// ^^

附言。如果您复制一个实例,行为将是未定义的,因为拷贝将指向相同的分配,并且两个实例都将尝试在析构函数中删除它。

简单的解决方案:不要使用裸指针。使用 RAII 容器,例如 std::vector如果您需要动态分配一个数组。


PPS。首先仔细考虑您是否需要动态分配(以及相关的开销)。在许多情况下,512 位是一个相当安全的就地大小。

关于c++ - 编译器忽略 operator new 分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55592246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com