c++ - 编辑字符串时接收内存泄漏

标签 c++ string memory-leaks console-application

string Player::CalcAsteroid(int _mass)
{
vector<BaseObject*>* tempObjects = GameState::GetObjects();

asteroid = "";

SetRadius(_mass / 100);
if (_mass < 100)
    SetRadius(1);

///////////////////////////////////////////////
// Nested for loops to draw a circle (asteroid)
///////////////////////////////////////////////

// x^2/a^2 + y^2/b^2 = 1

Player* p = dynamic_cast<Player*> ((*tempObjects)[0]);
int asteroidRadius = p->GetRadius();
double consoleRatio = 4.0 / 3.0; // Console characters do not have uniform H and W, so lets store the console ratio (4:3)
double a = consoleRatio*asteroidRadius; // The width is shorter than the height, so we'll multiply the ratio to the X radius (a)
double b = asteroidRadius; // The height need not change from the init radius

// Loop though each row...
for (int y = (int)-asteroidRadius; y <= asteroidRadius; y++)
{
    // and each column.
    for (int x = (int)floor(-consoleRatio*asteroidRadius); x <= consoleRatio*asteroidRadius; x++)
    {
        double d = (x / a)*(x / a) + (y / b)*(y / b); // Equation of a circle (see above)
        if (d > 0.90 && d < 1.1)
        {
            asteroid += (char)178; // The solid border (using gradient ASCII code)
        }
        //else if (d <= 1.1)
        //{
            //asteroid += 176; // The fill interior
        //}
        else
        {
            asteroid += " ";
        }
    }
    asteroid += '\n';
}
asteroid.replace(asteroid.size() / 2 - (name.size() / 2), name.size(), name); // Putting the name of the player in the center of the asteroid.
return asteroid;
}

所以我试图在控制台中重新调整玩家对象(一颗小行星)的大小。但是我似乎正在发生内存泄漏,实际上是一吨。每个似乎都与这个函数调用有关。 SetPicture(CalcAsteroid(GetMass()).c_str()); which的定义在这里

void SetPicture(const char * const _picture){ picture = _strdup(_picture);CalcWH(); }

计算WH();简单地计算碰撞数据中图像的字符宽度和高度。

Dropbox完整解决方案的链接。

先谢谢大家了!让我知道我是否可以做些什么来使我的问题更清楚,或者我是否有足够的信息。我是这个网站的新手,我希望养成良好的提问习惯。

最佳答案

内存泄漏的原因是 _strdup 的使用。这会为新字符串分配内存。您有责任在代码中的某处使用 free 释放内存。根据您发布的代码,您没有在任何地方调用 free

https://msdn.microsoft.com/en-us/library/y471khhc.aspx

如上链接所述:

_strdup 函数调用 ma​​lloc 为 strSource 的拷贝分配存储空间,然后将 strSource 复制到分配的空间。


我的建议是摆脱调用 _strdup 的工作,而只使用 std::string。 C++ 应用程序没有理由使用诸如 strdup 之类的函数。

关于c++ - 编辑字符串时接收内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223274/

相关文章:

c++ - 将 preincrement 结果强制转换为 void 的原因

JAVA - 将 "Stringed"数组解析为实际数组

Ruby跨平台EOF符号的写法

javascript - DOM 解析器 Chrome 扩展内存泄漏

c++ - 使用 RegisterClassEx 的问题

c++ - 如何让这个链表堆栈实现在 C++ 中运行?

c++ - Qt connect 无法识别 lambda 表达式

ios - 获取字符串显示的可选

caching - PHPExcel 内存耗尽

c++ - 你能给我一个内存泄漏的真实工作示例吗?