内存操作错误

Incorrect memory operation?

本文关键字:错误 操作 内存      更新时间:2023-10-16

请帮助查找此函数中的错误。

wchar_t* clean(wchar_t out[], const wchar_t in[])
{
    int n = wcslen(in);
    wchar_t *str = new wchar_t[n];
    wcscpy(str, in);
    out[0] = L'';
    wchar_t *state;
    wchar_t *word = wcstok(str, L" ", &state);
    while (NULL != word) {
        if (wcslen(word) > 1) {
            wcscat(out, word);
            wcscat(out, L" ");
        }
        word = wcstok(NULL, L" ", &state);
    }
    delete state;
    delete[] str;
    return out;
}

该函数从原始字符串中获取单词并将其放入结果字符串中。除了函数忽略多个空格和单个字母中的单词。

不幸的是,程序落在这个函数的最后几行,出现了同样的错误(linux-3.7, gcc-4.7):

*** Error in `./a.out': free(): invalid next size (fast): 0x08610338 ***

请解释一下我错在哪里?

  1. 移除delete state;state不是指向动态内存的指针,您可以从没有为其分配任何动态分配中看出这一点。它只是一个指针,指向一个已经存在的字符串。

  2. 修复new wchar_t[n]缓冲区溢出;

相关文章: