1

I have the following line in my main() function (which uses EasyBMP):

RGBApixel * myPixel = myFavoriteColor(192);

which is defined as:

RGBApixel * myFavoriteColor(int intensity)
{
RGBApixel color;
color.Red   = 0;
color.Green = intensity/2;
color.Blue  = intensity;
return &color;
}

and I'm getting the following error on a line that says "delete myPixel": malloc: * error for object 0x7fff5fbff9d0: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug

Why is it not getting allocated correctly?

joshholat
  • 3,371
  • 9
  • 39
  • 48

1 Answers1

1

You are returning the address of the local variable color which will not be valid after exiting the function myFavoriteColor. The object color will be destroyed at the end of the function. Instead return a copy the object RGBAPixel by chnaging the function signature to RGBAPixel myFavoriteColor(int) and using return color;

EDIT

You need to change RGBApixel * myPixel = myFavoriteColor(192); to RGBApixel myPixel = myFavoriteColor(192); as well. I believe you should read a C++ book before going further as these are very basic concepts.

Community
  • 1
  • 1
Naveen
  • 74,600
  • 47
  • 176
  • 233
  • That leads to: main.cpp:28: error: cannot convert ‘RGBApixel’ to ‘RGBApixel*’ in initialization – joshholat Jan 27 '11 at 06:28
  • Yeah, I know they're simple. I'm just beginning to learn. Is it at all possible to keep the RGBApixel's as pointers? – joshholat Jan 27 '11 at 06:36
  • It is possible to return `RGBApixel *` from the function. In that case you need to allocate memory for `color` usng `new RGBApixel();`. In this case memory will be allocated from heap and the object will still be valid outside the function. However, remember that you need to release the memory explictly using `delete myPixel;` (from main) in such case. To avoid this manual memory management you can use what is called a smart pointer such as `boost::shared_ptr`. – Naveen Jan 27 '11 at 06:39
  • Then I would do: RGBApixel * myFavoriteColor(int intensity) { RGBApixel * color = new RGBApixel(); color->Red = 0; color->Green = intensity/2; color->Blue = intensity; return color; } ?? – joshholat Jan 27 '11 at 06:50