【发布时间】:2014-10-23 00:28:20
【问题描述】:
我现在正在做作业。有一件事让我很困惑,我需要你的建议。
关于内存分配的问题非常简单和基本。学习C语言后,我目前正在学习C++ Primer这本书。所以我更喜欢使用new 和delete 来进行内存分配,这让我无法解决这个问题。这是问题所在。函数getNewFrameBuffer用于为framebuffer : (sizeof)Pixel x width x height分配内存,请注意Pixel是用户定义的数据类型。然后返回分配内存的指针。当我使用malloc() 函数时它工作正常,如下所示:
char* m_pFrameBuffer;
int width = 512, int height = 512;
//function call
getNewFrameBuffer(&m_pBuffer, width, height);
//function implementation using malloc
int getNewFrameBuffer(char **framebuffer, int width, int height)
{
*framebuffer = (char*)malloc(sizeof(Pixel) * width *height);
if(framebuffer == NULL)
return 0;
return 1;
}
但是,当我尝试使用 new 关键字分配内存时,会导致程序意外终止。这是我的代码:
int getNewFrameBuffer(char **framebuffer, int width, int height)
{
framebuffer = new char*[sizeof(Pixel) * width *height];
if(framebuffer == NULL)
return 0;
return 1;
}
我的代码有什么问题?非常感谢大家:)
【问题讨论】:
标签: c++ c pointers memory memory-management