RGBApixel memory issue with EasyBMP c++
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 th开发者_StackOverflowe 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 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.
精彩评论