mercredi 9 juin 2021

Unhandled memory exception on removing first and last characters

I am getting an unhandled exception on removing first and last characters, can someone please help me understand where i am making mistake:

int main()
{
    const char *pChar = " [{csfsfddfdfss}] ";
    int len = strlen(pChar);
    wchar_t *str = (wchar_t*)calloc(len, sizeof(wchar_t));  // L"";
    size_t cSize = len + 1;

    mbstowcs_s(&cSize, str, cSize, pChar, cSize);

    int length = wcslen(str);
    wchar_t *removeFirst = (wchar_t*)calloc(length+1, sizeof(wchar_t));
    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]) == (*empty)) && (first))
        {
            continue;
        }
        if (((str[i]) == (*brckt)) && (first))
        {
            first = false;
        }
        else 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]);
        }
    }

    length = wcslen(removeFirst);
    wchar_t *removeLast = (wchar_t*)calloc(length+1, sizeof(wchar_t));
    bool last = true;
    for (int i = (length - 1); i >= 0; i--)
    {
        const wchar_t *brckt = L"]";
        const wchar_t *empty = L" ";
        const wchar_t *curlyBrkt = L"}";
        if (((removeFirst[i]) == (*empty)) && (last))
        {
            continue;
        }
        if ((((removeFirst[i]) == (*brckt)) && (last)) || (((removeFirst[i]) == (*curlyBrkt)) && (last)))
        {
            last = false;
        }
        else if (((removeFirst[i]) == (*curlyBrkt)) && (last))
        {
            last = false;
            wchar_t *temp2 = (wchar_t*)calloc(length + 1, sizeof(wchar_t));
            wcsncat_s(temp2, (wcslen(temp2)+1) * 2, &removeFirst[i], 1);
            wcsncat_s(temp2, (wcslen(temp2)+1) * 2, removeLast, wcslen(removeLast));
            removeLast = temp2;
        }
        else
        {
            wchar_t *temp3 = (wchar_t*)calloc(length+1, sizeof(wchar_t));
            wcsncat_s(temp3, (wcslen(temp3)+1) * 2, &removeFirst[i], 1);
            wcsncat_s(temp3, (wcslen(temp3)+1) * 2, removeLast, wcslen(removeLast));
            removeLast = temp3;
            //removeLast = (removeFirst[i]) + removeLast;
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire