函数strncpy的奇怪行为?

时间:2013-11-18 10:21:17

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

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

status of variables

虽然我不知道为什么字符串后面有两个空格?!!!这是一个很大的项目,我不能在这里粘贴所有代码。以下只是一块。我的所有代码都是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;

1 个答案:

答案 0 :(得分:2)

如果源字符串长于最大字符数(即在您的情况下,如果strlen(target) > term_len成立,则

strncpy不会添加终止空字节。如果发生这种情况,subs可能会或可能不会被正确终止。

尝试将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--;
}
相关问题