做记忆时内存泄漏
Memory leaks while doing memcpy
我正在尝试编写一个处理ffmpeg的实用程序。一旦我需要将图像平面从一个指针复制到另一个指针。从AVPicture结构到我自己的结构。以下是一些来源。
我自己的框架结构。在构造函数中分配的内存,在析构函数中解除分配的内存
template <class DataType>
struct Frame
{
DataType* data; //!< Pointer to image data
int f_type; //!< Type of color space (ex. RGB, HSV, YUV)
int timestamp; //!< Like ID of frame. Time of this frame in the video file
int height; //!< Height of frame
int width; //!< Width of frame
Frame(int _height, int _width, int _f_type=0):
height(_height),width(_width),f_type(_f_type)
{
data = new DataType[_width*_height*3];
}
~Frame()
{
delete[] data;
}
};
这是执行转换的主循环。如果注释了带有memcpy的行,则根本没有内存泄漏。但是如果我取消注释它,则存在内存泄漏。
for(int i = begin; i < end; i++)
{
AVPicture pict;
avpicture_alloc(&pict, PIX_FMT_BGR24, _width, _height);
std::shared_ptr<Frame<char>> frame(new Frame<char>(_height, _width, (int)PIX_FMT_BGR24));
sws_scale(ctx, frame_list[i]->data, frame_list[i]->linesize, 0, frame_list[i]->height, pict.data, pict.linesize);
memcpy(frame->data,pict.data[0],_width*_height*3);
//temp_to_add->push_back(std::shared_ptr<Frame<char>>(frame));
avpicture_free(&pict);
}
我一直在尝试很多事情,例如:通过malloc分配内存并通过免费解除分配,手动将内存从pict复制到帧(在for循环中),使用std::copy和avpicture_layout ffmpeg辅助函数。无济于事。所以问题来了:我忘记了重要的事情吗?
我会感激每一个答案。
你确定这是一个泄漏,而不仅仅是你在内存中出错的事实吗?
如果您调用malloc()
或new
,该语言将允许您访问内存。但是,操作系统(在Windows,Linux或MacOS X等虚拟内存操作系统的情况下)实际上不会使页面成为任务工作集的一部分,直到您尝试使用该内存执行某些操作。
如果您认为泄漏是因为memcpy()
导致Windows进程资源管理器中的进程大小增加,那么这是一个不好的结论。即使您free()
或delete
对象,进程大小也不一定会减小。
以这两个测试用例为例。 两者都显然是零泄漏。
// test 1
int main()
{
volatile int *data = (volatile int *)malloc( (1 << 24) * sizeof(int) );
free((void *)data);
// Spin until killed, so we're visible in the process explorer as long as needed
while (1)
;
}
和
// test 2
int main()
{
volatile int *data = (volatile int *)malloc( (1 << 24) * sizeof(int) );
int i;
for (i = 0; i < (1 << 24); i++)
data[i] = i;
free((void *)data);
// Spin until killed, so we're visible in the process explorer as long as needed
while (1)
;
}
我怀疑第二个会在进程资源管理器中显示更大的内存足迹。 它应该超过 64MB。
这两个程序之间的区别在于,第二个程序实际上写入了它分配的内存,因此迫使操作系统实际使页面可用于任务。 一旦任务拥有页面,它通常不会将它们交还给操作系统。
(如果在上面的示例中确实发生了这种情况,请尝试较小的尺寸,例如(1<<18)或其他尺寸。 有时malloc
在这里确实很聪明,但通常不会。
您的类很容易在复制构造或分配时泄漏内存。您应该提供一个显式的复制构造函数和赋值运算符(至少禁止作为私有):
private:
Frame(const Frame<T>& rhs);
Frame<T>& operator=(const Frame<T>& rhs);
- C++功能泄漏内存,我是C++新手,不确定如何解决
- 我的堆栈弹出式磁带的实现是否泄漏内存?
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 析构函数 C++ 使泄漏内存
- 构造函数对象赋值是否泄漏内存
- corba :: orb_init泄漏内存
- Gmock泄漏内存
- 如何在不泄漏内存的情况下删除链接列表
- Visual C ODBC关闭记录集泄漏内存
- 为什么泄漏内存比在动态数组上执行 delete[] 慢
- OpenGL正在泄漏内存.哪个对象未释放
- 可以std ::退出泄漏内存
- uiautomation findall泄漏内存
- 为什么在此OpenCL代码中泄漏内存,为什么要泄漏内存
- pthread在完成后会泄漏内存
- win32 标准::线程泄漏内存
- 返回指向同一变量的指针是否会泄漏内存
- 使用clectType(new any_type())可能会泄漏内存泄漏
- Windows开发:如何确定我的应用程序是否正在泄漏内存
- WinHttp打开泄漏内存