문제

I don't think this requires another question, so I'm editing this extremely relevant one.

I had a code that would draw text by converting from char* to wchar_t*, and I suspected a memory error, as the program memory would go up as a crazy pace (5,000 K to 1,500,000 in minutes).

I suspected mbstowcs(), but I think I've found the problem now.

I am using a rather bad way of getting colors to draw things in general.

class MainClass {
    public:
        ID2D1SolidColorBrush* custom_color;
        ID2D1SolidColorBrush  get_rgba(float r, float g, float b, float a) {
            // render is a validated ID2D1RenderTarget*
            render->CreateSolidColorBrush(D2D1::ColorF(r,g,b,a),&custom_color);
            return custom_color;
        }
};

The memory usage increase is almost assuredly coming from this function. Are there any better ways I could return custom colors like this?

도움이 되었습니까?

해결책 3

My problem was in a code that returns an ID2D1SolidColorBrush* as the color variable, which was executing a Create() and not a Release every time it was called, so the brushes would build up and turn into memory leaks.

다른 팁

You don't appear to actually have a memory leak. And many "leaks" reported by memory leak tools are sometimes false positives. However, there's one easy fix to eliminate nxtx as a possible leak. Since you are allocating a fixed amount (250 chars) each time, you can easily allocate this off the stack:

    const int MY_MAX_STRING_SIZE = 1000;
    wchar_t ntxt[MY_MAX_STRING_SIZE]; // simple stack allocation
    mbstowcs(ntxt,text.c_str(),MY_MAX_STRING_SIZE);
    ntxt[MY_MAX_STRING_SIZE-1] = 0; //insure null termination
    render->DrawTextA(ntxt,text.length(),font,trect,color);
}

One thing I noticed is that your mbstowc call is specifying "size" as the max number of chars to copy, but is hardcoding 250 as the length. Are you certain you certain that "size" is always less than 250?

Its not lookikg as you have a memory leak. But there may be dangerous behaiour: mbstowcs accepts max length of wchar_t in dest, but you giving string length. Fix for this:

    int size=text.length()+1;
    enum { NTXT_LEN = 250 };
    wchar_t* ntxt= new wchar_t[NTXT_LEN];
    mbstowcs(ntxt, text.c_str(), NTXT_LEN);

Also, it is worth replacing raw new with something like scoped_array

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top