【问题标题】:How to allocate memory using C++ new instead of C malloc如何使用 C++ new 而不是 C malloc 分配内存
【发布时间】:2014-10-23 00:28:20
【问题描述】:

我现在正在做作业。有一件事让我很困惑,我需要你的建议。 关于内存分配的问题非常简单和基本。学习C语言后,我目前正在学习C++ Primer这本书。所以我更喜欢使用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;
}

我的代码有什么问题?非常感谢大家:)

【问题讨论】:

    标签: c++ c pointers memory memory-management


    【解决方案1】:
    *framebuffer = new char[sizeof(Pixel) * width *height];
    

    注意 *;

    【讨论】:

    • 您是在尝试创建字符指针数组还是指向字符数组的指针。因为看起来你也应该这样做 *framebuffer = new char[sizeof(Pixel) * width *height];
    • 哦,我明白了,我想创建一个字符数组。谢谢!!德鲁:)
    【解决方案2】:

    您应该使用new char 而不是new char* 分配,因为new char* 将分配那么多指针。 这导致您从*frameBuffer = 中删除了*,这意味着调用者的frameBuffer 参数不会被更改。

    换行

    *framebuffer = new char[sizeof(Pixel) * width *height];
    

    【讨论】:

    • 感谢 The Dark,您指出了问题并提供了解决方案:) 我会小心并尽力弄清楚我想要分配什么。谢谢!
    • 更 C++ 的做法是“new Pixel[width * height]”
    • 一个更 C++ 的方法是std::vector<Pixel>(width * height)
    • 嗨,Beanz 和 Chris,帧缓冲区是指向字符数组的指针。我认为编写 *framebuffer = new Pixel[width * height] 之类的代码是不对的。我说的对吗?
    • @Zengrui *framebuffer = new Pixel[width * height]; 分配Pixels 的数组并返回指向该数组的指针。这似乎比相同大小的char[] 更能满足您的需求。毕竟,我假设您会将Pixels 存储在帧缓冲区中。矢量解决方案的作用相同,但无需自己处理内存分配。如果您使用它,请先阅读std::vector
    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 2020-11-01
    • 2011-05-30
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    相关资源
    最近更新 更多