【问题标题】:Strange behavior with function strncpy?函数strncpy的奇怪行为?
【发布时间】:2013-11-18 10:21:16
【问题描述】:

在我的项目中,我遇到了strncpy 这些奇怪的问题。我检查了reference。但是函数strncpy 的行为让我很困惑。 在这个function,当它运行到strncpy(subs,target,term_len);

虽然我不知道为什么字符串后面有两个空格?!!!这是一个大项目,我不能在这里粘贴所有代码。以下只是一个片段。我所有的代码都是here

char* subs = new char[len];
while(top<=bottom){
    char* term = m_strTermTable[bottom].strterm;
    int term_len = strlen(term);
    memset(subs,'\0',len);
    strncpy(subs,target,term_len);
    int subs_len = strlen(subs);
    int re = strcmp(subs,term);
    if (re == 0)
    {
        return term_len;
    }
    bottom--;
}
delete[] subs;

【问题讨论】:

  • 如果这是c++,你为什么不直接使用std::strings?
  • strncpy not 总是添加空终止符。这是一个特别愚蠢的功能,我会避免使用。
  • 您检查过term_len 的值吗?会不会是term_lenlen 大?
  • 我在 SO 上看到的 每次使用 strncpy 都是毫无意义的。这些用途通常只是用数据损坏替换缓冲区溢出,就像这个一样。 极少种情况适合strncpy;没有经验的程序员没有充分的理由使用它。

标签: c++ visual-c++ visual-studio-debugging


【解决方案1】:

strncpy 如果源字符串长于最大字符数(即在您的情况下,如果strlen(target) &gt; term_len 成立),则不会添加终止空字节。如果发生这种情况,subs 可能会或可能不会正确地以 null 终止。

尝试将您的 strncpy 呼叫更改为

strncpy(subs, target, term_len-1);

因此,即使strncpy 没有添加终止空字节,subs 仍将由于之前的memset 调用而正确地以空值终止。

现在,话虽这么说 - 您可以完全避免使用单独的 subs 缓冲区(如果控制流到达 return 语句,无论如何都会泄漏),只需使用 strncmp 就可以了

while(top<=bottom) {
    char* term = m_strTermTable[bottom].strterm;
    int term_len = strlen(term);
    if (strncmp(term, target, term_len) == 0) {
        return term_len;
    }
    bottom--;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2019-06-03
    • 2011-06-14
    • 2020-01-31
    相关资源
    最近更新 更多