有时我在反转数组时会遇到 EXEC_BAD_ACCESS (访问冲突)
我正在使用 OpenEXR 库加载图像。
效果很好,只是加载的图像旋转了 180 度。我使用下面所示的循环来反转数组,但有时程序会退出,xcode 会给我一个 EXEC_BAD_ACCESS 错误(我认为这与 msvc 中的访问冲突相同)。不是每次都会出现,5-10次就出现一次。
理想情况下,我想就地反转数组,尽管这每次都会导致错误,并且使用 memcpy 会失败,但不会导致错误,只是一个空白图像。我想先知道是什么原因导致这个问题。
这是我正在使用的代码:(Rgba 是由 4 个“Half”sr、g、b 和 a 组成的结构,在 OpenEXR 中定义)
Rgba* readRgba(const char filename[], int& width, int& height){
Rgba* pixelBuffer = new Rgba[width * height];
Rgba* temp = new Rgba[width * height];
// ....EXR Loading code....
// TODO: *Sometimes* the following code results in a bad memory access error. No idea why.
// Flip the image to conform with OpenGL coordinates.
for (int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
temp[(i*width)+j] = pixelBuffer[(width*height)-(i*width)+j];
}
}
delete pixelBuffer;
return temp;
}
提前致谢!
I am loading an image using the OpenEXR library.
This works fine, except the image is loaded rotated 180 degrees. I use the loop shown below to reverse the array but sometimes the program will quit and xcode will give me an EXEC_BAD_ACCESS error (Which I assume is the same as an access violation in msvc). It does not happen everytime, just once every 5-10 times.
Ideally I'd want to reverse the array in place, although that led to errors everytime and using memcpy would fail but without causing an error, just a blank image. I'd like to know what's causing this problem first.
Here is the code I am using: (Rgba is a struct of 4 "Half"s r, g, b, and a, defined in OpenEXR)
Rgba* readRgba(const char filename[], int& width, int& height){
Rgba* pixelBuffer = new Rgba[width * height];
Rgba* temp = new Rgba[width * height];
// ....EXR Loading code....
// TODO: *Sometimes* the following code results in a bad memory access error. No idea why.
// Flip the image to conform with OpenGL coordinates.
for (int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
temp[(i*width)+j] = pixelBuffer[(width*height)-(i*width)+j];
}
}
delete pixelBuffer;
return temp;
}
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改
为:(
提示:想想当 i = 0 且 j = 0 时会发生什么!)
Change:
to:
(Hint: think about what happens when i = 0 and j = 0 !)
以下是如何优化此代码,以节省内存和循环:
请注意,最佳(从内存使用最佳实践的角度来看)是将 PixelBuffer* 作为参数传递并已分配。在同一段代码中分配和释放内存是一个很好的做法。
And here's how you can optimize this code, to save memory and for cycles:
Note that optimal (from a memory usage best practices point of view) would be to pass pixelBuffer* as a parameter and already allocated. It's a good practice to allocate and release the memory in the same piece of code.