如何使用C++new而不是C malloc来分配内存
How to allocate memory using C++ new instead of C malloc
我现在正在做家庭作业。有一件事让我很困惑,我需要你的建议。这个问题非常简单,而且是关于内存分配的基本问题。在学习了C语言之后,我现在正在学习《C++入门》一书。所以我更喜欢使用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;
}
我的代码出了什么问题?非常感谢大家:)
您应该使用new char
而不是new char*
进行分配,因为new char*
会分配那么多指针。这将导致您从*frameBuffer =
中删除*
,这意味着调用者的frameBuffer
参数将不会更改。
将线路更改为
*framebuffer = new char[sizeof(Pixel) * width *height];
*framebuffer = new char[sizeof(Pixel) * width *height];
注意*;
相关文章:
- 错误:malloc:对象 0x7f9edf504080 的 *** 错误:未分配正在释放的指针
- 如何通过 malloc 为队列数组分配内存?
- 是否可以使用 malloc 为类对象分配内存?
- 如何使用 "new" 而不是 malloc 分配内存?
- 从 JNI 调用的 DLL 从哪里获取其内存以进行分配,例如 Malloc
- malloc - 运行时内存指针类型分配
- malloc: 对象 0x00 的 *** 错误:未分配正在释放的指针
- 使用 new 而不是 malloc 分配 mem
- 由Malloc分配的结构,为什么?C 代码分析
- 我可以测试变量是否已使用 new 或 malloc 分配吗?
- 如果使用malloc分配的内存是使用delete而不是free删除的
- 使用运算符 new/malloc 分配的内存块是否可以在程序执行结束后持续存在
- malloc 分配的内存在什么时候获得类型
- malloc分配的对象动态类型是什么
- 我可以检查内存块(例如,使用 malloc 分配)是否保留在缓存中吗?
- 访问使用 malloc 分配的C++对象的成员
- 在汇编中使用malloc分配的内存-希望在c++中将其转换为三维数组
- 在Windows上,Malloc分配1 GiB内存失败
- 如何使用malloc分配映射键
- 在malloc分配的内存之外使用指针的预期行为