简体   繁体   English

如何使用C ++ new代替C malloc分配内存

[英]How to allocate memory using C++ new instead of C malloc

I am now working on homework. 我现在正在做作业。 There is one thing confused me and I need your advice. 有件事让我感到困惑,我需要您的建议。 The problem is quite simple and basic about memory allocation. 这个问题非常简单,而且是有关内存分配的基本知识。 I am currently studying the book C++ Primer after I learn C language. 学习C语言之后,我目前正在学习《 C ++ Primer》一书。 So I prefer to use new and delete to do the memory allocation which failed me for this problem. 因此,我更喜欢使用newdelete进行内存分配,这使我无法解决此问题。 Here is the problem. 这是问题所在。 The function getNewFrameBuffer is used to allocate allocate memory for framebuffer : (sizeof)Pixel x width x height , please note that Pixel is a user defined data type. 函数getNewFrameBuffer用于为framebuffer : (sizeof)Pixel x width x height分配内存framebuffer : (sizeof)Pixel x width x height ,请注意Pixel是用户定义的数据类型。 And then return the pointer of the allocated memory. 然后返回分配的内存的指针。 It works fine when I use malloc() function as below: 当我如下使用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;
}

However, when I try using new keyword to allocate memory it will cause an unexpected termination of the program. 但是,当我尝试使用new关键字分配内存时,它将导致程序意外终止。 Here is my code: 这是我的代码:

int getNewFrameBuffer(char **framebuffer, int width, int height)
{
     framebuffer = new char*[sizeof(Pixel) * width *height];
     if(framebuffer == NULL)
         return 0;
     return 1;
}

What's wrong with my code? 我的代码有什么问题? Thanks a lot, everyone:) 非常感谢大家:)

You should allocate using new char not new char* as new char* will allocate that many pointers. 您应该使用new char而不是new char*分配,因为new char*将分配那么多指针。 This has lead you to remove the * from *frameBuffer = meaning that the caller's frameBuffer parameter will not be changed. 这导致您从*frameBuffer =删除* ,这意味着不会更改调用方的frameBuffer参数。

Change the line to 将行更改为

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

注意*;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM