0

My code is as this:

// a function that new a char pointer and return it
Unsigned char* RGB2GS(Unsigned char* pRgb, int nw, int nh, int nbpp) {
    unsigned char* pGs = new unsigned char[nw*nh*nbpp];

    // code for rgb to gs...//
    return pGs;
}

int main() {
    unsigned char* pmyRgb = ReadBmp(filename);//size 1024x1024, RGB
    unsigned char* pMyGs = NULL;
    pMyGs = RGB2GS(pmyRgb, 1024, 1024, 24);
    delete[] pMyGs ;
    delete[] pmyRgb ; // correct typo

I found there is memory leakage(from VS2010 log). I created a pointer inside a function and return it. But I deleted the pointer outside the function. Is that a problem in this usage? thanks

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
manhon
  • 683
  • 7
  • 27
  • 1
    Why are you deleting twice? – Pubby May 04 '13 at 03:01
  • 1
    Also, writing code like this is just asking for leaks. Use RAII! – Pubby May 04 '13 at 03:02
  • why this code is asking for leaks? I tried to implement the function rgb2gs. I think it is more logical to created the GS char pointer inside it and return. But please tell me what is a better way to do so? thank a lot. – manhon May 04 '13 at 03:20
  • This is asking for leaks since if the `new` in `RGB2GS` throws, `pmyRgb` would never get deleted. Use `std::vector` instead. – Mankarse May 04 '13 at 06:16

2 Answers2

0

The leaked memory is probably the BMP data, pmyRgb. Check the docs for that function. You have deleted the memory at pMyGs just fine. Doing it twice isn't usually harmful but it is useless.

Jason
  • 1,612
  • 16
  • 23
0

Deleting a memory multiple times will have undefied behavior. There is nothing wrong in allocating a memory in a function, returning it, and deleting another place. Point to note is there is a difference between delete[] and delete, but since you are allocating memory as an array, delete[] is safe to use.

The difference between delete and delete [] in C++enter link description here

Community
  • 1
  • 1
Bill
  • 5,263
  • 6
  • 35
  • 50
  • sorry, i made a typo. should be: delete[] pMyGs ; delete[] pmyRgb ; so I guess my code should not have memory leakage, right? – manhon May 04 '13 at 03:18
  • looking at the code that you have pasted, I dnt see any leaks :) – Bill May 04 '13 at 03:19