我的 main() 函数(使用 EasyBMP)中有以下行:
RGBApixel * myPixel = myFavoriteColor(192);
定义为:
RGBApixel * myFavoriteColor(int intensity)
{
RGBApixel color;
color.Red = 0;
color.Green = intensity/2;
color.Blue = intensity;
return &color;
}
我在“delete myPixel”行中收到以下错误:malloc: * error for object 0x7fff5fbff9d0: pointer being freed was not allocated * 在malloc_error_break 设置断点调试
为什么没有正确分配?
最佳答案
您正在返回局部变量 color
的地址,该地址在退出函数 myFavoriteColor
后将无效。对象 color
将在函数结束时被销毁。而是通过将函数签名更改为 RGBAPixel myFavoriteColor(int)
并使用 return color;
RGBAPixel
的拷贝
编辑
您还需要将 RGBAPIxel * myPixel = myFavoriteColor(192);
更改为 RGBAPIxel myPixel = myFavoriteColor(192);
。我相信你应该阅读 C++ book在继续之前,因为这些是非常基本的概念。
关于c++ - EasyBMP c++ 的 RGBApixel 内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4813292/