如何使用C++new而不是C malloc来分配内存

How to allocate memory using C++ new instead of C malloc

本文关键字:malloc 分配 内存 何使用 C++new      更新时间:2023-10-16

我现在正在做家庭作业。有一件事让我很困惑,我需要你的建议。这个问题非常简单,而且是关于内存分配的基本问题。在学习了C语言之后,我现在正在学习《C++入门》一书。所以我更喜欢使用newdelete来进行内存分配,这让我在这个问题上失败了。问题来了。函数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];

注意*;