【发布时间】:2021-06-10 00:23:25
【问题描述】:
我将以下包含 std::wstring 的代码转换为 wchar_t(下一个代码块),但出现内存转储错误:
下面是带有 std::wstring 的代码:
std::wstring RemoveFirstAndLast(std::wstring str)
{
std::wstring removeFirst = L"";
bool first = true;
for (std::wstring::iterator it = str.begin(); it != str.end(); ++it)
{
const wchar_t *brckt = L"[";
const wchar_t *empty = L" ";
const wchar_t *curlyBrkt = L"{";
if (((*it) == (*curlyBrkt)) && (first))
{
first = false;
removeFirst = removeFirst + (*it);
}
else
{
removeFirst = removeFirst + (*it);
}
}
std::wstring removeLast = L"";
bool last = true;
for (std::wstring::reverse_iterator it = removeFirst.rbegin(); it != removeFirst.rend(); ++it)
{
const wchar_t *brckt = L"]";
const wchar_t *empty = L" ";
const wchar_t *curlyBrkt = L"}";
if (((*it) == (*curlyBrkt)) && (last))
{
last = false;
removeLast = (*it) + removeLast;
}
else
{
removeLast = (*it) + removeLast;
}
}
return removeLast;
}
下面是与上面相同的代码,但带有 wchar_t*:
wchar_t* RemoveFirstAndLast(wchar_t *str)
{
wchar_t *removeFirst = L"";
int length = wcslen(str);
bool first = true;
for (int i = 0; i < length; i++)
{
const wchar_t *brckt = L"[";
const wchar_t *empty = L" ";
const wchar_t *curlyBrkt = L"{";
if (((str[i]) == (*curlyBrkt)) && (first))
{
first = false;
wcsncat_s(removeFirst, (wcslen(removeFirst) + 1) * 2, &str[i], 1); //removeFirst = removeFirst + (str[i]);
}
else
{
wcsncat_s(removeFirst, (wcslen(removeFirst) + 1) * 2, &str[i], 1); //removeFirst = removeFirst + (str[i]);
}
}
wchar_t *removeLast = L"";
length = wcslen(removeFirst);
bool last = true;
for (int i = length; i >= 0; i--)
{
const wchar_t *brckt = L"]";
const wchar_t *empty = L" ";
const wchar_t *curlyBrkt = L"}";
if (((removeFirst[i]) == (*curlyBrkt)) && (last))
{
last = false;
wchar_t *temp2 = (wchar_t*)calloc((wcslen(removeLast) * 2) + 1, sizeof(wchar_t));
wcsncat_s(temp2, (wcslen(temp2)) * 2, &removeFirst[i], 1);
wcsncat_s(temp2, (wcslen(temp2)) * 2, removeLast, wcslen(removeLast));
removeLast = temp2;
}
else
{
wchar_t *temp3 = (wchar_t*)calloc((wcslen(removeLast) * 2) + 1, sizeof(wchar_t));
wcsncat_s(temp3, (wcslen(temp3)) * 2, &removeFirst[i], 1);
wcsncat_s(temp3, (wcslen(temp3)) * 2, removeLast, wcslen(removeLast));
removeLast = temp3;
//removeLast = (removeFirst[i]) + removeLast;
}
}
return removeLast;
}
代码正在尝试删除第一个和最后一个字符。作为一个初学者,我试图理解为什么在简单地将代码从 std::wstring 转换为 wchar_t* 时会出现错误?该错误会创建内存转储?有人可以帮我理解我在哪里犯错了吗?
【问题讨论】:
-
具体是什么“内存转储错误”?
-
使用您的调试器和编译器的地址清理程序。两者都是有价值的信息来源,也是找出代码存在的任何内存问题的好工具。
-
wcsncat_s(removeFirst (...从根本上被破坏了,因为您没有为removeFirst分配任何内存。事实上,我很惊讶wchar_t *removeFirst = L"";编译 - 如果将代码编译为 C++,它应该是const wchar_t *removeFirst = L"";。 -
@PaulSanders:非常感谢……这很有帮助。你能帮我理解如何分配内存,这将非常有用。
-
@chris:这些是保罗所说的错误类型