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?
You are returning the address of the local variable
colorwhich will not be valid after exiting the functionmyFavoriteColor. The objectcolorwill be destroyed at the end of the function. Instead return a copy the objectRGBAPixelby chnaging the function signature toRGBAPixel myFavoriteColor(int)and usingreturn color;EDIT
You need to change
RGBApixel * myPixel = myFavoriteColor(192);toRGBApixel myPixel = myFavoriteColor(192);as well. I believe you should read a C++ book before going further as these are very basic concepts.