Wednesday, March 31, 2010

Re: [Cpp-Programming] Why would this fail?

Well first off, you have a major memory leak:  whenever you have a call to new (or new[]), there should always be an associated call to delete (or delete[]).

Typically, what you do is pass in a buffer, and let the caller handle the delete (like memcpy does); however, in your case since it's just a temp array, you can simply do your computation in a local variable and copy the results back to your original array:

void bitmap::flipVertically()
{
    BYTE* temp = new BYTE[width*height]; //instead of "dwn*acc"
    for(int index=0; index < height; index++) {
        int reverseIndex = (height-1) - index;
        memcpy(&temp[reverseIndex*width],
            &bits[index*width], width);
    }
    memcpy(bits, temp, height*width);
    delete[] temp;
    //No need to return anything now!
}

There is also a way to do this without so large an array; do you see how?

As a general rule, you should never be returning pointers you allocated with new from a function.  This is something programmers coming from managed languages (C#, Java, etc.) often find quite surprising.

Hope this helps!
  -BlueRaja


On Wed, Mar 31, 2010 at 12:56 PM, JoeC <enki034@yahoo.com> wrote:
I have this piece of code that simply copies one array into another it
worked for a while now it fails what could make this fail?



bits = new BYTE[acc*dwn];
...

       bits = flip();

BYTE* bitmap::flip(){

 BYTE * temp = new BYTE[acc*dwn];

 for (int index=0; index < dwn; index++)
  // memcpy(&temp[((dwn-1) - index)*acc],
   //       &bits[index*acc], acc);


 return temp;

--
You received this message because you are subscribed to the Google Groups "C++ Programming" group.
To post to this group, send email to cpp-programming@googlegroups.com.
To unsubscribe from this group, send email to cpp-programming+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cpp-programming?hl=en.


--
You received this message because you are subscribed to the Google Groups "C++ Programming" group.
To post to this group, send email to cpp-programming@googlegroups.com.
To unsubscribe from this group, send email to cpp-programming+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cpp-programming?hl=en.

0 Comments:

Post a Comment

<< Home