Home > database >  C Project has triggered a breakpoint in Visual Studio 2019
C Project has triggered a breakpoint in Visual Studio 2019

Time:11-01

I am new to using pointers (and Visual Studio too) and I'm trying to make a function which deletes the spaces ' ' from a const array. The function should return another array but without the spaces. Seems pretty simple, the code works in Codeblocks, but in Visual Studio it keeps triggering breakpoints. Any idea what am I doing wrong?

char* removeSpaces(const char* text) {
    int length = strlen(text);
    char* clone = new char(strlen(text));
    strcpy_s(clone,length 1, text);
    int i = 0;
    do {
        if (clone[i] == ' ')
            strcpy(clone   i, clone   i   1);
        i  ;
    } while (i < length);

    return clone;
}

What appears after I run the code

CodePudding user response:

"It works" is the most devious form of undefined behaviour, as it can trick you into believing that something is correct - you're writing outside your allocated memory, and strcpy is undefined when the source and destination overlap.

You used the wrong form of memory allocation:

  • new char(100): a single char with the value 100
  • new char[100]: an array of one hundred chars.

(And you need space for the string terminator.)

You also don't need to first copy the input and then laboriously modify the copy by shifting characters, and you don't need strcpy for copying a single character.

Just reserve some space, and then copy only the characters you want to keep from the input.

char* removeSpaces(const char* text)
{
    int length = strlen(text);
    char* clone = new char[length 1];
    int copy_length = 0
    for (int original = 0; original < length; original  )
    {
        if (text[original] != ' ')
        {
            clone[copy_length] = text[original];
            copy_length  ;
        }
    }
    clone[copy_length] = 0;
    return clone;
}

CodePudding user response:

Thanks to dratenik and user1810087 I managed to use strings and found the solution, thanks.

char* removeSpaces(const char* text) {
    int length = strlen(text);
    string clone(text);

    clone.erase(remove_if(clone.begin(), clone.end(), isspace), clone.end());

    char* cclone = new char(clone.length());

    for (int i = 0; i <= clone.length(); i  )
        cclone[i] = clone[i];

    return cclone;
}
  • Related