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. So I prefer to use new
and delete
to do the memory allocation which failed me for this problem. 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. And then return the pointer of the allocated memory. It works fine when I use malloc()
function as below:
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. 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:)