【问题标题】:C++ Project has triggered a breakpoint in Visual Studio 2019C++ 项目在 Visual Studio 2019 中触发了断点
【发布时间】:2021-12-16 01:26:55
【问题描述】:

我不熟悉使用指针(以及 Visual Studio),我正在尝试创建一个函数,从 const 数组中删除空格 ' '。该函数应该返回另一个数组但没有空格。看起来很简单,代码在 Codeblocks 中工作,但在 Visual Studio 中它不断触发断点。知道我做错了什么吗?

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

【问题讨论】:

  • 您需要添加更多关于 Visual Studio 如何破坏的详细信息(屏幕截图或其他内容)
  • char* clone = new char(strlen(text)); 好像有点奇怪,你是说char* clone = new char[strlen(text)];吗?
  • strcpy(clone + i, clone + i + 1);(复制重叠字符串)的行为未定义。它可能会起作用,它可能会可怕地爆炸,可能三者都有。
  • 如果要使用 C++,请使用字符串。如果您使用的是字符串:remove_if(str.begin(), str.end(), isspace);

标签: c++ visual-studio dynamic-memory-allocation breakpoints


【解决方案1】:

感谢 dratenik 和 user1810087 我设法使用字符串并找到了解决方案,谢谢。

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;
}

【讨论】:

    【解决方案2】:

    “它可以工作”是未定义行为的最狡猾的形式,因为它可以诱使您相信某些事情是正确的——您在分配的内存之外写入,而当源和目标重叠时,strcpy 是未定义的。

    你使用了错误的内存分配形式:

    • new char(100):单个char,值为100
    • new char[100]:一百个chars 的数组。

    (而且您需要为字符串终止符留出空间。)

    您也不需要先复制输入,然后费力地通过移位字符修改副本,并且复制单个字符也不需要strcpy

    只需保留一些空间,然后从输入中仅复制要保留的字符。

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多