【问题标题】:Problem: String writes over another string问题:字符串覆盖另一个字符串
【发布时间】:2019-02-26 22:33:44
【问题描述】:

我正在尝试使用以下代码处理两个字符串。结果工作得很好,但是每当我尝试对第二个字符串执行相同的操作时,第一个字符串就会被第二个字符串的值覆盖。例如,如果第一个字符串 =“fuhg”,第二个字符串等于“abc”,第一个字符串变为:“abcg”。 它可能与内存分配或类似的东西有关,但我无法弄清楚,因为我在那个领域不是很好。

string newPassChar;
string newBloom=bloomFilter(newPass); 
int index=0;
for ( int k =0 ; k < alpha.length() ; k++ )
{
    if (newBloom[k]=='1')
      { 
        newPassChar[index]=alpha[k];
      index++;
      }
}

【问题讨论】:

  • 您需要确保newBloom[k]newPassChar[index]alpha[k] 不会越界。也就是说,如果您需要帮助调试代码,请提供minimal reproducible example

标签: c++ string memory memory-management


【解决方案1】:

来自cppreference std::basic_string::operator[]

No bounds checking is performed. If pos > size(), the behavior is undefined.

来自cppreference std::basic_string construcor

1) Default constructor. Constructs empty string (zero size and unspecified capacity).

所以:

string newPassChar;

使用size() == 0 创建新字符串。

然后:

newPassChar[0] = ...

将覆盖字符串中的空字符。但是在下一次迭代中,当index = 1,那么:

newPassChar[1] = ....

它是undefined behavior。并产生恶魔。

我认为您想在阅读字符时“推回”字符:

        newPassChar.push_back(alpha[k]);

不需要存储另一个用于索引字符串的“索引”变量,它知道字符串对象本身的大小,它在size()方法中可用。

【讨论】:

  • pos == size() 定义明确。只有修改它是不确定的。
  • @Deduplicator 我没看清楚,cppreference 说对于pos == size(),版本reference operator[]( size_type pos ); 在C++11 之前是未定义的行为。由于C++11它返回一个对空字符的引用,所以它定义了,有空字符。
  • @KamilCuk 请注意,从 C++11 开始,在 pos == size() 时读取 char 是明确定义的行为,但在 pos == size() 时写入 char 对于任何 @ 仍然是未定义的行为987654340@ 其他值 '\0'。大概是因为引用是指向位于内存中其他位置的静态char 以代替空字符串的空终止符。
猜你喜欢
  • 2013-08-22
  • 2015-01-04
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 2012-04-08
  • 2011-09-26
  • 1970-01-01
相关资源
最近更新 更多