简体   繁体   English

C ++,调试断言失败

[英]C++, Debug Assertion Failed

Debug Assertion Failed 调试断言失败

I spend a lot of time trying to fond out why I have an assert in this code. 我花了很多时间试图弄清楚为什么我在这段代码中有一个断言。

If there is no string in the class, it's work well. 如果类中没有字符串,则效果很好。

Can you explaine, why I have an Assert whit the class containing string. 你能解释一下,为什么我有一个断言的类包含字符串。

Thank's Marc 谢谢马克

#include <malloc.h>
#include <string>

class CTheClassWith_string
{
private:
    std::string TheName_;
};

class CTheClassWith_int
{
private:
    int TheName_;
};

int main()
{
std::string theString;
int size;

CTheClassWith_int   TheClassWith_int;
CTheClassWith_string TheClassWith_string;

CTheClassWith_int* pTheClassWith_int = new CTheClassWith_int;
size = _msize(pTheClassWith_int);
delete pTheClassWith_int;

CTheClassWith_string* pTheClassWith_string = new CTheClassWith_string;
size = _msize(pTheClassWith_string);
delete pTheClassWith_string;

CTheClassWith_int* pArrayTheClassWith_int = new CTheClassWith_int[2];
size = _msize(pArrayTheClassWith_int);
delete [] pArrayTheClassWith_int;

CTheClassWith_string* pArrayTheClassWith_string = new CTheClassWith_string[2];
size = _msize(pArrayTheClassWith_string);             // Why I assert on this line
delete [] pArrayTheClassWith_string;

return 0;
}

As from your question I understood you want to determine the size in bytes allocated from heap, when using new() or new[]() . 根据您的问题,我知道您想确定使用new()new[]()时从堆分配的字节大小。

Well, you cannot use the _msize() function to achieve this. 好吧,您不能使用_msize()函数来实现此目的。 Besides it's a legacy function, the pointers obtained with new aren't necessarily coming from underlying calls to functions from the malloc() family (which _msize() relies on in turn, thus the assertion). 除了它是一个遗留函数外,用new获得的指针不一定来自malloc()系列的底层调用( _msize()依次依赖于该断言,因此是断言)。

To determine sizes allocated from the heap (or elsewhere), you can always rely on the sizeof() operator: 要确定从堆(或其他地方)分配的大小,您始终可以依赖sizeof()运算符:

CTheClassWith_int* pTheClassWith_int = new CTheClassWith_int;
size = sizeof(CTheClassWith_int);
delete pTheClassWith_int;

CTheClassWith_string* pTheClassWith_string = new CTheClassWith_string;
size = sizeof(CTheClassWith_string);
delete pTheClassWith_string;

CTheClassWith_int* pArrayTheClassWith_int = new CTheClassWith_int[2];
size = sizeof(CTheClassWith_int) * 2;
delete [] pArrayTheClassWith_int;

CTheClassWith_string* pArrayTheClassWith_string = new CTheClassWith_string[2];
size = sizeof(CTheClassWith_string) * 2;
delete [] pArrayTheClassWith_string;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM